Usage | image-optimizer-go | Spatie       

 SPATIE  

image-optimizer-go
==================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Image-optimizer-go](https://spatie.be/docs/image-optimizer-go/v1)  Usage

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/image-optimizer-go/v1) 

  Usage    
- [ Introduction ](https://spatie.be/docs/image-optimizer-go/v1/introduction)
- [ Installation and setup ](https://spatie.be/docs/image-optimizer-go/v1/installation-and-setup)
- [ Usage ](https://spatie.be/docs/image-optimizer-go/v1/usage)
- [ Which tools will do what? ](https://spatie.be/docs/image-optimizer-go/v1/which-tools-will-do-what)
- [ Logging the optimization process ](https://spatie.be/docs/image-optimizer-go/v1/logging-the-optimization-process)
- [ Example conversions ](https://spatie.be/docs/image-optimizer-go/v1/example-conversions)
- [ Testing ](https://spatie.be/docs/image-optimizer-go/v1/testing)
- [ Releasing ](https://spatie.be/docs/image-optimizer-go/v1/releasing)
- [ Changelog ](https://spatie.be/docs/image-optimizer-go/v1/changelog)
- [ Support us ](https://spatie.be/docs/image-optimizer-go/v1/support-us)

 Usage
=====

###  On this page 

1. [ Setting a timeout ](#content-setting-a-timeout)
2. [ Handling errors ](#content-handling-errors)
3. [ Creating your own optimization chains ](#content-creating-your-own-optimization-chains)
4. [ Writing a custom optimizer ](#content-writing-a-custom-optimizer)
5. [ Writing an optimizer without a binary ](#content-writing-an-optimizer-without-a-binary)

This is the default way to use the package:

```
chain := imageoptimizer.New()
err := chain.Optimize(ctx, "image.jpg")
```

The image will be overwritten by an optimized version which should be smaller. The package automatically decides which tools can handle the image. Missing binaries are logged like other optimizer failures and skipped by default.

To keep the original image, use `OptimizeTo`:

```
err := chain.OptimizeTo(ctx, "original.jpg", "optimized.jpg")
```

The source remains untouched. Both paths must be local files or local `file://` URLs and the destination directory must exist. Input and output must not name the same file, including hard links and symlinks. Unsupported formats pass through unchanged.

Optimizers write in place. A tool can produce a larger image or leave partial output when it fails. Keep a backup of important originals. This port preserves PHP's in-place behavior, not the Rust port's optional safe-output/reporting additions.

Setting a timeout
-----------------------------------------------------------------------------------------------------------

You can set the maximum time each individual optimizer in a chain can use:

```
chain.Timeout = 10 * time.Second
err := chain.Optimize(ctx, "image.jpg")
```

The default is 60 seconds per optimizer. Zero disables that deadline. AVIF decode and encode share one deadline. Custom optimizers must honor the supplied context. Go cannot forcibly interrupt application code that ignores it. A canceled caller context always stops the chain, even in continue mode.

Handling errors
-----------------------------------------------------------------------------------------------------

By default, when an optimizer fails, the failure is logged and the chain simply continues with the next optimizer. To return the failure and stop:

```
chain.Throws = true
err := chain.Optimize(ctx, "image.jpg")
```

Set `Throws` to false for the default log-and-continue behavior. Or supply an error handler to decide for yourself. The handler receives the error, the optimizer that failed and the image being optimized. Return nil to continue, or an error to abort:

```
chain.OnError = func(err error, failed imageoptimizer.Optimizer, image imageoptimizer.Image) error {
    slog.Error("Optimization failed", "tool", failed.Name(), "path", image.Path(), "error", err)
    return nil
}
```

`OnError` takes precedence over `Throws`. Per-optimizer timeouts flow through the same mechanism. Use `errors.Is(err, context.DeadlineExceeded)` for deadlines. Use `errors.As` with `*imageoptimizer.ProcessError` to inspect combined process output and the wrapped startup or exit error. Validation and output-copy errors always return directly and never reach `OnError`.

Creating your own optimization chains
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------

If you want to customize the chain of optimizers you can add optimizers manually. Here's an example where we only want jpegoptim and optipng:

```
chain := imageoptimizer.NewChain(
    imageoptimizer.Jpegoptim.WithOptions("--strip-all", "--all-progressive"),
    imageoptimizer.Optipng.WithOptions("-o2"),
)
```

`WithOptions` replaces all default options. Each string is one literal argument. Use `"-q", "85"`, not `"-q 85"`. No shell expansion occurs. Inspect or replace the ordered `chain.Optimizers` slice, or append with `append`:

```
webp := imageoptimizer.Cwebp.WithOptions("-q", "80")
webp.BinaryPath = "/opt/image-tools/bin"
webp.BinaryName = "cwebp"
chain.Optimizers = append(chain.Optimizers, webp)
```

`BinaryName` overrides the encoder executable and `DecodeBinaryName` overrides the AVIF decoder. Empty names use the tool's standard name. `BinaryPath` is a directory, or empty to search `PATH`. Change `Options` to replace arguments. `Command(ctx, input, output)` returns the shell-free encoder command for inspection or custom execution. For AVIF, its input must already be decoded PNG.

To change default quality, use `NewWithQuality(q)`. It accepts 0 through 100 and returns `(*Chain, error)`. JPEG, PNG and WebP use `q`, while AVIF uses `round(63 - q * 0.63)`.

Writing a custom optimizer
--------------------------------------------------------------------------------------------------------------------------------------

Want to use another command line utility to optimize your images? No problem. Implement the `Optimizer` interface:

```
type Optimizer interface {
    Name() string
    CanHandle(imageoptimizer.Image) bool
    Optimize(context.Context, imageoptimizer.Image, *slog.Logger) error
}
```

Use `exec.CommandContext` for a native process. Return errors rather than panicking and clean up your own temporary files with `defer`. Images expose `Path()`, `Extension()` and `MIME() (string, error)`. MIME is detected from the current contents, not the extension.

Writing an optimizer without a binary
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------

Sometimes an optimizer has no binary and no shell command to run, for example one that sends the image to an external optimization API. The same interface supports these self-handling optimizers without dummy binary methods:

```
type APIOptimizer struct {
    Run func(context.Context, string) error
}

func (APIOptimizer) Name() string { return "api" }

func (APIOptimizer) CanHandle(image imageoptimizer.Image) bool {
    mime, err := image.MIME()
    return err == nil && mime == "image/jpeg"
}

func (o APIOptimizer) Optimize(ctx context.Context, image imageoptimizer.Image, logger *slog.Logger) error {
    logger.InfoContext(ctx, "Optimizing via API", "path", image.Path())
    return o.Run(ctx, image.Path())
}
```

Add an instance to `chain.Optimizers` just like a binary optimizer. Write optimized bytes back to the image path and propagate failures. The chain passes its logger and per-optimizer context to your implementation.

Configure chains before using them. Concurrent optimization of different files is supported when your optimizers, logger handler and error handler support it. Do not mutate chain configuration during optimization or optimize the same file concurrently.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
