imagemeta

package module
v1.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2026 License: MIT Imports: 25 Imported by: 21 modules, 13 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Tests on Linux, MacOS and Windows codecov GoDoc

Reading and writing image metadata

This library is primarily about reading image metadata, with limited support for writing common metadata fields (copyright, creator, title, description, date and GPS position) to images without existing metadata via Write.

I welcome PRs with fixes, but please raise an issue first if you want to add new features.

Supported formats

Format EXIF IPTC XMP CONFIG
JPEG ✓ ✓ ✓ ✓
TIFF ✓ ✓ ✓ ✓
PNG ✓ ✓ ✓ ✓
WebP ✓ ✓ ✓
HEIF/HEIC ✓ ✓ ✓
AVIF ✓ ✓ ✓
JPEG XL ✓ ✓ ✓
RAW (DNG, CR2, NEF, ARW, PEF) ✓ ✓ ✓ ✓
GIF ✓

CONFIG includes the frame count for GIF, animated PNG (APNG), WebP and AVIF/HEIF image sequences. JPEG XL animations are not detected and always report 1 frame.

JPEG XL files often store EXIF and XMP Brotli compressed (e.g. cjxl does this by default). We didn't want to force a Brotli decoder into everyone's build, so you need to provide one via the DecompressBrotli option to read these, e.g. using andybalholm/brotli:

imagemeta.Decode(imagemeta.Options{
	// ...
	DecompressBrotli: func(r io.Reader) io.Reader { return brotli.NewReader(r) },
})

If not set, compressed metadata is skipped with a warning.

Note that this library has no dependencies outside of the standard library and golang.org/x/text. The Brotli decoder is only imported by our tests, so it will not be compiled into your binary, but as with our other test dependencies, it will show up in e.g. go mod graph, go list -m all and your go.sum.

Performance

Extracting EXIF performs well, ref. the benhcmark below. Note that you can get a significant boost if you only need a subset of the fields (e.g. only the Orientation). The last line is with the library that Hugo used before it was replaced with this.

BenchmarkDecodeCompareWithGoexif/bep/imagemeta/exif/jpeg/alltags-10                68658             15825 ns/op            3034 B/op        128 allocs/op
BenchmarkDecodeCompareWithGoexif/bep/imagemeta/exif/jpeg/orientation-10           444249              2567 ns/op             501 B/op         11 allocs/op
BenchmarkDecodeCompareWithGoexif/rwcarlsen/goexif/exif/jpg/alltags-10              27206             44110 ns/op          141977 B/op        816 allocs/op

When in doubt, Exiftool is right

The output of this library is tested against exiftool -n -json. This means, for example, that:

  • We use f-numbers and not APEX for aperture values.
  • We use seconds and not APEX for shutter speed values.
  • EXIF field definitions are fetched from this table: https://exiftool.org/TagNames/EXIF.html
  • IPTC field definitions are fetched from this table: https://exiftool.org/TagNames/IPTC.html
  • The XMP handling is currently very simple, you can supply your own XMP handler (see the HandleXMP option) if you need more.

There are some subtle differences in output:

  • Exiftool prints rationale number arrays as space formatted strings with a format/precision that seems unnecessary hard to replicate, so we use strconv.FormatFloat(f, 'f', -1, 64) for these.

Development

Many of the tests depends on generated golden files. To update these, run:

 go generate ./gen

Note that you need a working exiftool and identify(ImageMagick) in your PATH for this to work. identify will fail for the truncated RAW fixtures unless ImageMagick is built with libraw (Homebrew's is not); the generator then keeps the committed .config.json for those. This was tested OK with:

exiftool -ver
12.76

Debugging tips:

 exiftool testdata/goexif_samples/has-lens-info.jpg -htmldump > dump.html

Documentation

Index

Constants

View Source
const UnknownPrefix = "UnknownTag_"

UnknownPrefix is used as prefix for unknown tags.

Variables

View Source
var ErrMetadataExists = errors.New("image already contains metadata")

ErrMetadataExists is returned by Write when the image already contains EXIF or XMP metadata.

View Source
var (
	// ErrStopWalking is a sentinel error to signal that the walk should stop.
	ErrStopWalking = fmt.Errorf("stop walking")
)

Functions

func CanWrite added in v1.2.0

func CanWrite(f ImageFormat) bool

CanWrite reports whether Write supports format f.

func IsInvalidFormat

func IsInvalidFormat(err error) bool

IsInvalidFormat reports whether the error was an InvalidFormatError.

func Write added in v1.2.0

func Write(opts WriteOptions) error

Write copies the image in opts.R to opts.W with opts.Meta added. It returns ErrMetadataExists (wrapped) if the image already contains metadata and an InvalidFormatError if the image could not be parsed.

Types

type DecodeResult added in v0.13.0

type DecodeResult struct {
	// ImageConfig contains basic image configuration.
	// Note that this will be zero if the CONFIG source was not requested.
	ImageConfig ImageConfig
}

DecodeResult contains the result of a Decode operation.

func Decode

func Decode(opts Options) (result DecodeResult, err error)

Decode reads the metadata and passes it to the provided handlers in the options. It returns a DecodeResult containing the image configuration if the CONFIG source was requested.

type HandleTagFunc

type HandleTagFunc func(info TagInfo) error

HandleTagFunc is the function that is called for each tag.

type ImageConfig added in v0.13.0

type ImageConfig struct {
	Width  int
	Height int

	// FrameCount is the number of frames in the image, 1 for still images.
	// It's read for GIF, animated PNG (APNG), WebP and AVIF/HEIF image sequences.
	FrameCount int
}

ImageConfig contains basic image configuration.

type ImageFormat

type ImageFormat int

ImageFormat is the image format.

const (
	// ImageFormatAuto signals that the image format should be detected automatically (not implemented yet).
	ImageFormatAuto ImageFormat = iota
	// JPEG is the JPEG image format.
	JPEG
	// TIFF is the TIFF image format.
	TIFF
	// PNG is the PNG image format.
	PNG
	// WebP is the WebP image format.
	WebP
	// HEIF is the HEIF/HEIC image format (ISO Base Media File Format with HEVC codec).
	HEIF
	// AVIF is the AVIF image format (ISO Base Media File Format with AV1 codec).
	AVIF
	// DNG is the DNG (Digital Negative) RAW image format.
	DNG
	// CR2 is the Canon CR2 RAW image format.
	CR2
	// NEF is the Nikon NEF RAW image format.
	NEF
	// ARW is the Sony ARW RAW image format.
	ARW
	// PEF is the Pentax PEF RAW image format.
	PEF
	// JXL is the JPEG XL image format.
	JXL
	// GIF is the GIF image format. Only the CONFIG source is supported.
	GIF
)

func (ImageFormat) String

func (i ImageFormat) String() string

type InvalidFormatError

type InvalidFormatError struct {
	Err error
}

InvalidFormatError is used when the format is invalid.

func (*InvalidFormatError) Error

func (e *InvalidFormatError) Error() string

func (*InvalidFormatError) Is added in v0.6.0

func (e *InvalidFormatError) Is(target error) bool

Is reports whether the target error is an InvalidFormatError.

type LatLong added in v1.2.0

type LatLong struct {
	Lat  float64
	Long float64
}

LatLong is a GPS position in decimal degrees.

type Meta added in v1.2.0

type Meta struct {
	Copyright   string
	Creator     string
	Title       string
	Description string
	Date        time.Time

	// LatLong is the GPS position in decimal degrees.
	LatLong *LatLong
}

Meta is the metadata to write to an image. Zero values are not written.

func (Meta) IsZero added in v1.2.0

func (m Meta) IsZero() bool

IsZero reports whether m has no metadata to write.

func (Meta) Validate added in v1.2.0

func (m Meta) Validate() error

Validate reports whether m can be written.

type Options

type Options struct {
	// The Reader (typically a *os.File) to read image metadata from.
	R io.ReadSeeker

	// The image format in R.
	ImageFormat ImageFormat

	// If set, the decoder skip tags in which this function returns false.
	// If not set, a default function is used that skips all EXIF tags except those in IFD0.
	ShouldHandleTag func(tag TagInfo) bool

	// The function to call for each tag.
	HandleTag HandleTagFunc

	// The default XMP handler decodes each rdf:Description using Go's xml package and passes
	// each property to HandleTag: attributes, child elements with text content or an
	// rdf:resource reference, and rdf:Seq/Bag/Alt lists (a single item as a string, several
	// as a []string). Struct-valued properties are not decoded.
	// If HandleXMP is set, the decoder will call this function for each XMP packet instead.
	// Note that r must be read completely.
	HandleXMP func(r io.Reader) error

	// If set, the decoder will only read the given tag sources.
	// Note that this is a bitmask and you may send multiple sources at once.
	Sources Source

	// Warnf will be called for each warning.
	Warnf func(string, ...any)

	// DecompressBrotli, if set, is used to decompress Brotli compressed metadata,
	// e.g. EXIF and XMP stored in brob boxes in JPEG XL images.
	// If not set, Brotli compressed metadata is skipped with a warning.
	// The tests use https://github.com/andybalholm/brotli:
	//
	//	DecompressBrotli: func(r io.Reader) io.Reader { return brotli.NewReader(r) }
	DecompressBrotli func(r io.Reader) io.Reader

	// Timeout is the maximum time the decoder will spend on reading metadata.
	// Mostly useful for testing.
	// If set to 0, the decoder will not time out.
	Timeout time.Duration

	// LimitNumTags is the maximum number of tags to read.
	// Default value is 5000.
	LimitNumTags uint32

	// LimitTagSize is the maximum size in bytes of a tag value to read.
	// Tag values larger than this will be skipped without notice.
	// Note that this limit is not relevant for the XMP source.
	// Default value is 10000.
	LimitTagSize uint32
	// contains filtered or unexported fields
}

Options contains the options for the Decode function.

type Rat

type Rat[T int32 | uint32] interface {
	Num() T
	Den() T
	Float64() float64

	// String returns the string representation of the rational number.
	// If the denominator is 1, the string will be the numerator only.
	String() string
}

Rat is a rational number.

func NewRat

func NewRat[T int32 | uint32](num, den T) (Rat[T], error)

NewRat returns a new Rat with the given numerator and denominator.

type Source added in v0.5.0

type Source uint32

Source is a bitmask and you may send multiple sources at once.

const (
	// EXIF is the EXIF tag source.
	EXIF Source = 1 << iota
	// IPTC is the IPTC tag source.
	IPTC
	// XMP is the XMP tag source.
	XMP

	// CONFIG source, which currently the image dimensions encoded in the image.
	// Note that this may not be the same as the dimensions stored in EXIF tags.
	CONFIG
)

func (Source) Has added in v0.5.0

func (t Source) Has(source Source) bool

Has returns true if the given source is set.

func (Source) IsZero added in v0.5.0

func (t Source) IsZero() bool

IsZero returns true if the source is zero.

func (Source) Remove added in v0.5.0

func (t Source) Remove(source Source) Source

Remove removes the given source.

func (Source) String added in v0.5.0

func (i Source) String() string

type TagInfo

type TagInfo struct {
	// The tag source.
	Source Source
	// The tag name.
	Tag string
	// The tag namespace.
	// For EXIF, this is the path to the IFD, e.g. "IFD0/GPSInfoIFD"
	// For XMP, this is the namespace, e.g. "http://ns.adobe.com/camera-raw-settings/1.0/"
	// For IPTC, this is the record tag name as defined https://exiftool.org/TagNames/IPTC.html
	Namespace string
	// The tag value.
	Value any
}

TagInfo contains information about a tag.

type Tags

type Tags struct {
	// contains filtered or unexported fields
}

Tags is a collection of tags grouped per source.

func (*Tags) Add

func (t *Tags) Add(tag TagInfo)

Add adds a tag to the correct source.

func (Tags) All

func (t Tags) All() map[string]TagInfo

All returns all tags in a map.

func (*Tags) EXIF

func (t *Tags) EXIF() map[string]TagInfo

EXIF returns the EXIF tags.

func (Tags) GetDateTime

func (t Tags) GetDateTime() (time.Time, error)

GetDateTime tries to find a date/time value from available metadata sources. It checks EXIF first (DateTimeOriginal, DateTime), then XMP (DateTimeOriginal, CreateDate, DateCreated), and finally IPTC (DateCreated + TimeCreated).

func (Tags) GetLatLong

func (t Tags) GetLatLong() (lat float64, long float64, err error)

GetLatLong returns the latitude and longitude from available metadata sources. It checks EXIF first, then falls back to XMP.

func (*Tags) Has

func (t *Tags) Has(tag TagInfo) bool

Has reports if a tag is already added.

func (*Tags) IPTC

func (t *Tags) IPTC() map[string]TagInfo

IPTC returns the IPTC tags.

func (*Tags) XMP

func (t *Tags) XMP() map[string]TagInfo

XMP returns the XMP tags.

type WriteOptions added in v1.2.0

type WriteOptions struct {
	// R is the image to add metadata to.
	// It must not contain any EXIF or XMP metadata,
	// which is the case for images created by Go's (and Hugo's) image encoders.
	R io.Reader

	// W is where the image with metadata gets written.
	W io.Writer

	// The image format in R. See CanWrite for the supported formats.
	ImageFormat ImageFormat

	// The metadata to write. It is written as both EXIF and XMP,
	// except for Title, which has no common EXIF tag.
	Meta Meta
}

WriteOptions contains the options for the Write function.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址