Encoding and responses
Introduction
Encoding turns an image into a file in a format. You may send the file as a response, save it to a path, store it on a storage disk, or keep the bytes. Each of these returns the first error the image's modifiers met, so you handle every error in one place.
Responding with an image
image.Response encodes the image and returns a 200 OK *web.Response with the format's Content-Type:
func Show(r *web.Request) *web.Response {
img, err := image.From(r).Open("resources/images/hero.jpg")
if err != nil {
return web.Fail(err)
}
return image.Response(img.Cover(1200, 630, image.Center), image.WEBP, image.Quality(80))
}A format of "" keeps the format the image was decoded from, or JPEG for an image created in code. When encoding fails, the response renders the error the same way web.Fail does.
Encoding
Encode returns an *image.Encoded, which holds the file's bytes and its format:
encoded, err := img.Encode(image.PNG)
if err != nil {
return err
}
encoded.Bytes() // the PNG file
encoded.MediaType() // "image/png"
encoded.DataURI() // "data:image/png;base64,iVBORw0KGgo..."The format may also be any name image.FormatOf reads, such as "jpg", ".webp", or "image/png".
Quality
image.Quality sets the quality of lossy formats from 0 to 100, and defaults to 75. JPEG and WebP use it, and the other formats ignore it. WebP at quality 100 encodes losslessly:
img.Encode(image.JPEG, image.Quality(85))
img.Encode(image.WEBP, image.Quality(100)) // losslessFormat details
| Format | Notes |
|---|---|
| JPEG | Lossy. Transparent pixels blend over the image's background color. |
| PNG | Lossless, with transparency. |
| GIF | Every frame of an animation, mapped to the 216-color web-safe palette. |
| WebP | Lossy at quality 0 to 99, lossless at 100. See WebP encoding. |
| BMP | Transparent pixels blend over the image's background color. |
| TIFF | Lossless, compressed with Deflate. |
| AVIF, HEIC | Return an error that matches image.ErrNotSupported. |
Go's encoders write no metadata, so encoded files have no Exif data or color profiles.
Saving files
Save encodes the image in the format of the path's extension and writes it:
if err := img.Scale(800, 0).Save("storage/app/photos/cat-800.webp"); err != nil {
return err
}For an image read with Open, an empty path writes back to the file it came from.
Storing on disks
Store encodes the image in the format of the path's extension and writes it to a storage disk:
err := img.Cover(256, 256, image.Center).Store(r, storage.From(r), "avatars/42.webp")