All formats

golang.org/x/image/tiff

LanguageGo
LicenseBSD 3-Clause
Repositorygo.googlesource.com/image (GitHub mirror)
Documentationpkg.go.dev/golang.org/x/image/tiff
Depends onnothing (pure Go)
Read / writeread: 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#

Shell
go get golang.org/x/image/tiff

Basic usage: decode a TIFF and save as PNG#

Go
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#

Go
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#

Go
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:

Go
import (
	"image"
	_ "image/jpeg"
	_ "image/png"

	_ "golang.org/x/image/tiff"
)

img, format, err := image.Decode(f)  // format is "tiff"

Tips#