golang.org/x/image/tiff
| Language | Go |
|---|---|
| License | BSD 3-Clause |
| Repository | go.googlesource.com/image (GitHub mirror) |
| Documentation | pkg.go.dev/golang.org/x/image/tiff |
| Depends on | nothing (pure Go) |
| Read / write | read: first page, strips and tiles, uncompressed, LZW, Deflate, PackBits, CCITT Group 3/4; write: uncompressed or Deflate. No BigTIFF, no JPEG compression |
golang.org/x/image/tiff is part of the Go project’s supplementary image packages. It plugs into the standard image package: after importing it, image.Decode recognizes TIFF files. It decodes grayscale, palette, RGB and RGBA images with 1 to 16 bits per sample into the matching image.Image type (*image.Gray, *image.Paletted, *image.RGBA, *image.NRGBA64 and so on).
It’s small and has a simple API (3 functions), but it reads only the first image of a multi-page file, doesn’t support BigTIFF, JPEG-compressed TIFF, CMYK or floating point samples, and gives no access to tags.
Installation#
go get golang.org/x/image/tiff
Basic usage: decode a TIFF and save as PNG#
package main
import (
"fmt"
"image/png"
"log"
"os"
"golang.org/x/image/tiff"
)
func main() {
in, err := os.Open("in.tif")
if err != nil {
log.Fatal(err)
}
defer in.Close()
img, err := tiff.Decode(in)
if err != nil {
log.Fatal(err)
}
fmt.Println(img.Bounds().Dx(), "x", img.Bounds().Dy())
out, err := os.Create("out.png")
if err != nil {
log.Fatal(err)
}
defer out.Close()
if err := png.Encode(out, img); err != nil {
log.Fatal(err)
}
}
How to get TIFF dimensions without decoding#
f, err := os.Open("in.tif")
if err != nil {
log.Fatal(err)
}
defer f.Close()
cfg, err := tiff.DecodeConfig(f)
if err != nil {
log.Fatal(err)
}
fmt.Println(cfg.Width, "x", cfg.Height, cfg.ColorModel)
How to write a TIFF with Deflate compression#
out, err := os.Create("out.tif")
if err != nil {
log.Fatal(err)
}
defer out.Close()
err = tiff.Encode(out, img, &tiff.Options{Compression: tiff.Deflate})
if err != nil {
log.Fatal(err)
}
Pass nil options for an uncompressed file. The encoder accepts only tiff.Uncompressed and tiff.Deflate; the other CompressionType constants (LZW, CCITTGroup3, CCITTGroup4) return an “unsupported compression” error.
How to decode TIFF with image.Decode#
Import the package for its side effect to let image.Decode detect TIFF next to other formats:
import (
"image"
_ "image/jpeg"
_ "image/png"
_ "golang.org/x/image/tiff"
)
img, format, err := image.Decode(f) // format is "tiff"
Tips#
- The decoder buffers everything it reads in memory when the reader doesn’t implement
io.ReaderAt; pass an*os.Filefor large files. - For multi-page files, tags or BigTIFF, call libtiff through cgo or use GDAL bindings such as godal.