imaging
| Language | Go |
|---|---|
| License | MIT |
| Repository | github.com/disintegration/imaging |
| Documentation | pkg.go.dev/github.com/disintegration/imaging |
| Depends on | golang.org/x/image (BMP and TIFF codecs) |
| Read / write | yes / yes (uses x/image/bmp) |
imaging adds image operations to Go: resize with Lanczos and other filters, fit and fill for thumbnails, crop, rotate, flip, blur, sharpen and color adjustments. imaging.Open and imaging.Save handle BMP, PNG, JPEG, GIF and TIFF, choosing the format from the file extension.
BMP reading and writing goes through golang.org/x/image/bmp, so the same limits apply: no RLE or 16-bit BMP input. Processing functions return *image.NRGBA, which is saved as a 24-bit BMP when all pixels are opaque and as 32-bit otherwise.
Installation#
Shell
go get github.com/disintegration/imaging
Basic usage: open, resize and save a BMP#
Go
package main
import (
"log"
"github.com/disintegration/imaging"
)
func main() {
img, err := imaging.Open("in.bmp")
if err != nil {
log.Fatal(err)
}
// width 640, height 0 keeps the aspect ratio
small := imaging.Resize(img, 640, 0, imaging.Lanczos)
if err := imaging.Save(small, "out.bmp"); err != nil {
log.Fatal(err)
}
}
How to convert BMP to PNG or JPEG#
The output format comes from the extension:
Go
img, err := imaging.Open("in.bmp")
if err != nil {
log.Fatal(err)
}
if err := imaging.Save(img, "out.png"); err != nil {
log.Fatal(err)
}
if err := imaging.Save(img, "out.jpg", imaging.JPEGQuality(90)); err != nil {
log.Fatal(err)
}
How to convert PNG to BMP#
BMP has no reliable transparency, so place the image on a white background first:
Go
import (
"image"
"image/color"
"github.com/disintegration/imaging"
)
src, err := imaging.Open("in.png")
if err != nil {
log.Fatal(err)
}
bg := imaging.New(src.Bounds().Dx(), src.Bounds().Dy(), color.White)
flat := imaging.Overlay(bg, src, image.Pt(0, 0), 1.0) // fully opaque: saved as 24-bit
err = imaging.Save(flat, "out.bmp")
How to write a BMP to an HTTP response#
Go
func handler(w http.ResponseWriter, r *http.Request) {
img, err := imaging.Open("in.png")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "image/bmp")
imaging.Encode(w, imaging.Grayscale(img), imaging.BMP)
}
Tips#
imaging.Opendetects the format from the file contents, so it reads.dibfiles too.imaging.Savepicks the format from the extension and doesn’t know.dib: useimaging.Encode(w, img, imaging.BMP)for such names.imaging.Grayscalestill returns an*image.NRGBA, saved as 24-bit. For an 8-bit gray BMP, copy into an*image.Grayand usebmp.Encode.