imgdiet-go – git.sr.ht/~jamesponddotco/imgdiet-go Index | Files | Directories

package imgdiet

import "git.sr.ht/~jamesponddotco/imgdiet-go"

Package imgdiet provides high-performance image resizing, format conversion, and compression optimized for web delivery. The package wraps the libvips image processing library using vipsgen.

Supported Formats

The package supports the following image formats for both input and output:

Input format is automatically detected from file contents using magic bytes.

Usage

Initialize libvips before processing any images, and shut it down when done:

func main() {
	imgdiet.Start(imgdiet.DefaultConfig())
	defer imgdiet.Stop()

	// Process images...
}

Open an image from any io.Reader, process it, and export to the desired format:

img, err := imgdiet.Open(ctx, file)
if err != nil {
	return err
}

opts := imgdiet.DefaultOptions()
opts.Width = 800
opts.Quality = 75

output, err := img.Export(ctx, imgdiet.FormatWebP, opts)
if err != nil {
	return err
}

Each call to Image.Export works from the original image data, allowing multiple exports with different formats or settings without quality loss from repeated processing:

webp, _ := img.Export(ctx, imgdiet.FormatWebP, opts)
avif, _ := img.Export(ctx, imgdiet.FormatAVIF, opts)
jpeg, _ := img.Export(ctx, imgdiet.FormatJPEG, opts)

Configuration

Use Config to control libvips memory usage and concurrency. The DefaultConfig function returns settings suitable for most server environments.

Use Options to control image output dimensions, quality, and format-specific encoding parameters. The DefaultOptions function returns settings optimized for web delivery.

Requirements

This package requires libvips 8.18 or later to be installed on the system. See the libvips documentation for installation instructions.

Index

Constants

const (
	// ErrOpenImage is returned when an image cannot be opened.
	ErrOpenImage xerrors.Error = "failed to open image"

	// ErrExportImage is returned when an image cannot be exported.
	ErrExportImage xerrors.Error = "failed to export image"

	// ErrNilReader is returned when a nil reader is provided.
	ErrNilReader xerrors.Error = "reader is nil"

	// ErrNilContext is returned when a nil context is provided.
	ErrNilContext xerrors.Error = "context is nil"
)
const ErrUnsupportedFormat xerrors.Error = "unsupported image format"

ErrUnsupportedFormat is returned when the image format is not supported by this package.

Functions

func Start

func Start(cfg *Config)

Start initializes the libvips library with the given configuration.

Start must be called before any image processing operations and should be called exactly once during application startup. Calling Start multiple times may result in undefined behavior.

If cfg is nil, DefaultConfig is used.

func Stop

func Stop()

Stop shuts down the libvips library and releases all associated resources.

Stop should be called once when the application is finished processing images, typically via defer immediately after Start. After Stop is called, no further image processing operations should be performed.

Types

type Config

type Config struct {
	// Cache specifies the maximum size of the libvips operation cache in bytes.
	// The operation cache stores intermediate results to accelerate repeated
	// processing of similar images.
	//
	// Larger values improve performance for repetitive workloads but increase
	// memory consumption. If zero, caching is disabled entirely.
	Cache int

	// MaxConcurrency specifies the maximum number of threads libvips uses for
	// image processing operations. Each operation may use multiple threads for
	// parallel processing of image regions.
	//
	// Higher values improve throughput on multi-core systems but increase
	// memory usage, as each thread maintains its own working buffers. If zero,
	// libvips uses a single thread.
	MaxConcurrency int

	// ReportLeaks enables memory leak detection in libvips. When enabled,
	// libvips logs any unreleased allocations when the library shuts down.
	//
	// This is intended for debugging and development use only, as leak
	// detection adds overhead to memory operations.
	ReportLeaks bool
}

Config defines the runtime configuration for the libvips image processing library, the underlying library that powers imgdiet.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a Config instance suitable for server environments with moderate memory availability.

The defaults balance throughput and memory usage:

type Format

type Format int

Format represents an image format supported by the package.

const (
	// FormatUnknown represents an unknown or unsupported image format.
	FormatUnknown Format = iota
	FormatJPEG
	FormatPNG
	FormatGIF
	FormatWebP
	FormatAVIF
	FormatHEIF
	FormatTIFF
)

Supported image formats.

func DetectFormat

func DetectFormat(image []byte) (Format, error)

DetectFormat identifies the image format by examining magic bytes. It returns FormatUnknown and ErrUnsupportedFormat for unrecognized formats.

func (Format) String

func (f Format) String() string

String returns a human-readable string representation of the format.

type Image

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

Image represents a loaded image and manages its lifecycle.

func Open

func Open(ctx context.Context, r io.Reader) (*Image, error)

Open reads image data from r and returns an Image ready for processing.

The entire contents of r are read into memory to enable multiple exports with different settings. For very large images, ensure sufficient memory is available.

func (*Image) Export

func (i *Image) Export(format Format, opts *Options) ([]byte, error)

Export encodes the image to the specified format and returns the result.

Export returns three values: the encoded image data, the number of bytes saved compared to the original, and any error. The bytes saved value may be negative if the output is larger than the original, which can occur when converting to less efficient formats or using high quality settings.

Each call to Export decodes from the original image data, preserving full quality regardless of how many times the image is exported. This allows exporting to multiple formats without compounding compression artifacts:

webp, savedWebP, _ := img.Export(ctx, imgdiet.FormatWebP, opts)
avif, savedAVIF, _ := img.Export(ctx, imgdiet.FormatAVIF, opts)

If opts is nil, DefaultOptions is used.

func (*Image) Format

func (i *Image) Format() Format

Format returns the detected format of the original image.

func (*Image) Size

func (i *Image) Size() int64

Size returns the size of the original image in bytes.

type Options

type Options struct {
	// Width specifies the target width in pixels.
	//
	// If zero, the original width is preserved. If only Width is specified,
	// Height is calculated to maintain aspect ratio.
	Width int

	// Height specifies the target height in pixels.
	//
	// If zero, the original height is preserved. If only Height is specified,
	// Width is calculated to maintain aspect ratio.
	Height int

	// Effort controls the CPU effort spent on encoding, ranging from 0
	// (fastest) to 9 (slowest, best compression). Higher values produce smaller
	// files at the cost of encoding speed.
	//
	// This setting applies to GIF, WebP, and AVIF.
	Effort int

	// Quality specifies the lossy compression quality, ranging from 1 (lowest)
	// to 100 (highest). Higher values produce larger files with better visual
	// fidelity.
	//
	// This setting applies to JPEG, WebP, AVIF, and HEIF.
	Quality int

	// Compression specifies the PNG compression level, ranging from 0 (no
	// compression, fastest) to 9 (maximum compression, slowest). This affects
	// file size and encoding time but not image quality, as PNG is lossless.
	Compression int

	// Speed controls the AVIF encoder speed preset, ranging from 0 (slowest,
	// best compression) to 9 (fastest, largest files). This is similar to
	// Effort, but specific to AVIF encoding.
	Speed int

	// TileWidth specifies the TIFF tile width in pixels.
	//
	// If zero, the encoder uses strip-based encoding instead of tiled encoding.
	// When set, TileHeight should also be specified.
	TileWidth int

	// TileHeight specifies the TIFF tile height in pixels.
	//
	// If zero, the encoder uses strip-based encoding instead of tiled encoding.
	// When set, TileWidth should also be specified.
	TileHeight int

	// Bitdepth specifies the number of bits per channel in the output image.
	// Valid values are 1, 2, 4, 8, and 16. If zero, the encoder preserves the
	// original bit depth or uses a format-appropriate default.
	Bitdepth int

	// QuantTable selects the JPEG quantization table, ranging from 0 to 8.
	QuantTable int

	// Dither specifies the amount of Floyd-Steinberg dithering to apply when
	// reducing color depth for palette-based formats. Values range from 0.0 (no
	// dithering) to 1.0 (full dithering).
	//
	// Dithering reduces banding artifacts but may introduce noise.
	Dither float64

	// Interlaced enables progressive encoding for JPEG and PNG, or interlaced
	// encoding for GIF. Progressive images render incrementally, displaying a
	// low-quality preview before the full image loads.
	Interlaced bool

	// StripMetadata removes EXIF, XMP, IPTC, and ICC profile data from the
	// output image.
	//
	// This reduces file size but discards information such as camera settings,
	// GPS coordinates, and color profiles.
	StripMetadata bool

	// OptimizeICCProfile converts embedded ICC color profiles to sRGB and
	// removes the profile from the output. This reduces file size while
	// maintaining color accuracy for displays using the sRGB color space.
	OptimizeICCProfile bool

	// OptimizeCoding enables Huffman table optimization for JPEG encoding. This
	// produces smaller files with a modest increase in encoding time.
	OptimizeCoding bool

	// TrellisQuant enables trellis quantization for JPEG encoding. This
	// rate-distortion optimization technique produces smaller files at
	// equivalent quality levels, at the cost of slower encoding.
	TrellisQuant bool

	// OvershootDeringing enables overshoot deringing for JPEG encoding. This
	// reduces ringing artifacts near sharp edges in the image.
	OvershootDeringing bool

	// OptimizeScans enables progressive scan optimization for JPEG encoding.
	// This reorders the spectral data in progressive JPEGs for improved
	// compression.
	//
	// Only effective when Interlaced is true.
	OptimizeScans bool

	// Lossless enables mathematically lossless encoding for WebP and AVIF.
	//
	// The output image will be pixel-identical to the input, but file sizes
	// will be significantly larger than lossy encoding.
	Lossless bool

	// NearLossless enables near-lossless encoding for WebP. This preprocessing
	// step slightly modifies the image to improve compression while minimizing
	// perceptible quality loss.
	//
	// Only effective when Lossless is true.
	NearLossless bool

	// SmartSubsample enables context-dependent chroma subsampling for WebP.
	// This adaptively applies subsampling based on image content, preserving
	// detail in areas with sharp color transitions.
	SmartSubsample bool

	// Pyramid enables multi-resolution pyramid generation for TIFF output.
	//
	// Pyramid TIFFs store the image at multiple resolutions, enabling efficient
	// display at different zoom levels.
	Pyramid bool
}

Options controls the export behavior for images.

Zero values for numeric fields indicate that the encoder should use its default value or preserve the original image property.

func DefaultOptions

func DefaultOptions() *Options

DefaultOptions returns an Options instance configured for web-optimized image export.

The defaults prioritize smaller file sizes over maximum quality, making them suitable for web delivery where bandwidth and load times are important. Metadata is stripped for privacy and reduced file size, and ICC profiles are converted to sRGB for broad display compatibility.

Image dimensions are preserved by default.

Source Files

config.go doc.go image.go imgdiet.go options.go

Directories

PathSynopsis
internal
Version
v1.0.0 (latest)
Published
Jan 18, 2026
Platform
linux/amd64
Imports
9 packages
Last checked
4 weeks ago

Tools for package owners.