imaging

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: MIT Imports: 51 Imported by: 0

Documentation

Overview

Package imaging inspects and transforms bounded, untrusted raster images. Plans are immutable declarations. An Engine owns concurrent processing calls; callers retain ownership of input readers and the engine's lifecycle.

Index

Constants

View Source
const DefaultAVIFQuality = 60

DefaultAVIFQuality is used unless a plan selects AVIFQuality.

View Source
const DefaultAVIFSpeed = 10

DefaultAVIFSpeed favors fast encoding. Zero, when explicitly selected with AVIFSpeed, requests the most thorough search; it is not an omitted setting.

View Source
const DefaultWebPMethod = 4
View Source
const DefaultWebPQuality = 75
View Source
const MaxFontBytes = 8 << 20
View Source
const MaxPathCommands = 1024
View Source
const (
	MaxTextRunes = 4096
)
View Source
const MaxTransforms = 32

Variables

View Source
var ErrNativeUnavailable = safeerror.New("native image capability is unavailable")

ErrNativeUnavailable matches a missing, disabled or incompatible native runtime, or a requested native capability absent from the installed libvips build.

Functions

func Module

func Module(name foundation.ProviderID, key foundation.Key[*Engine], config Config) foundation.Module

Module constructs the configured engine and drains its actual operations at shutdown. Applications borrow the resolved engine; the module closes it.

Types

type Backend

type Backend uint8

Backend selects native discovery. AutoBackend is the default: portable codecs always work and an installed libvips runtime adds native capabilities. LibvipsBackend requires discovery to succeed at construction. PortableBackend disables native discovery. No custom build tag or libvips headers are needed.

const (
	PortableBackend Backend = iota
	LibvipsBackend
	AutoBackend
)

type BlendMode

type BlendMode uint8

BlendMode combines straight RGB channels before source-over alpha composition.

const (
	BlendNormal BlendMode = iota
	BlendMultiply
	BlendScreen
	BlendOverlay
	BlendDarken
	BlendLighten
	BlendDifference
	BlendExclusion
)

type Capabilities

type Capabilities struct {
	Backend              Backend
	Formats              []FormatCapability
	ColorManagement      bool
	MetadataPreservation bool
	SmartCrop            bool
}

Capabilities is an owned snapshot of this engine's available functionality.

func (Capabilities) ForFormat

func (c Capabilities) ForFormat(format Format) (FormatCapability, bool)

type Config

type Config struct {
	Backend   Backend
	Limits    Limits
	MaxActive int
	Timeout   time.Duration
}

func DefaultConfig

func DefaultConfig() Config

func (Config) Validate

func (c Config) Validate() error

type CropInterest

type CropInterest uint8

CropInterest selects the libvips heuristic used by SmartFill.

const (
	CropAttention CropInterest = iota
	CropEntropy
)

type Engine

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

Engine owns admission and cancellation, not input readers. Close requests cancellation and waits for actual operation exit; Done is never optimistic. Codec/transform calls are synchronous. Cancellation is observed between codec operations and rows; a codec already running retains its capacity until exit.

func New

func New(config Config) (*Engine, error)

func (*Engine) Capabilities

func (e *Engine) Capabilities() Capabilities

func (*Engine) Close

func (e *Engine) Close(ctx context.Context) error

func (*Engine) Create

func (e *Engine) Create(ctx context.Context, width, height int, background color.NRGBA, plan Plan) (Result, error)

Create starts from a solid canvas and executes a plan under the same limits and admission ownership as Process. The default output format is PNG.

func (*Engine) Done

func (e *Engine) Done() <-chan struct{}

func (*Engine) Format

func (*Engine) Format(s fmt.State, _ rune)

func (*Engine) Inspect

func (e *Engine) Inspect(ctx context.Context, data []byte) (Info, error)

Inspect examines input with this engine's codecs, limits and admission owner. The package-level Inspect function always uses portable codecs.

func (*Engine) Limits

func (e *Engine) Limits() Limits

func (*Engine) NativeError

func (e *Engine) NativeError() error

NativeError reports why this engine cannot use native features. It is nil when libvips is ready. Applications may inspect it during startup; an automatic engine remains usable for portable operations when native discovery fails.

func (*Engine) Process

func (e *Engine) Process(ctx context.Context, source io.Reader, plan Plan) (Result, error)

Process reads at most the remaining InputBytes+1 after accounting for layers, checks the complete plan before decoding pixels, and publishes no output on failure. It does not close source.

func (*Engine) ProcessBytes

func (e *Engine) ProcessBytes(ctx context.Context, data []byte, plan Plan) (Result, error)

ProcessBytes runs the same bounded pipeline directly on data without copying it. data must not change during the call.

func (*Engine) Validate

func (e *Engine) Validate() error

func (*Engine) ValidatePlan

func (e *Engine) ValidatePlan(p Plan) error

type Font

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

Font owns an immutable TrueType/OpenType font. Load application font assets once and reuse them across plans; mutable font faces never escape the engine. Font loading is for application assets, not arbitrary uploaded fonts.

func BuiltinFont

func BuiltinFont(style FontStyle) (Font, error)

BuiltinFont loads one of the Go fonts already included with Foundry. Apps need no font download, filesystem path or additional Go dependency.

func ParseFont

func ParseFont(data []byte) (Font, error)

ParseFont copies data before parsing. Collections, WOFF and bitmap/color fonts are not supported by this portable outline renderer.

func (Font) Format

func (Font) Format(s fmt.State, _ rune)

func (Font) GoString

func (Font) GoString() string

func (Font) String

func (Font) String() string

type FontStyle

type FontStyle uint8
const (
	FontRegular FontStyle = iota
	FontBold
	FontItalic
	FontBoldItalic
	FontMono
)

type Format

type Format string
const (
	JPEG Format = "jpeg"
	PNG  Format = "png"
	WebP Format = "webp"
	GIF  Format = "gif"
	BMP  Format = "bmp"
	TIFF Format = "tiff"
	AVIF Format = "avif"
	ICO  Format = "ico"
	HEIF Format = "heif"
	// HEIC is HEIF encoded with HEVC; both names use the canonical HEIF format.
	HEIC     Format = HEIF
	JPEG2000 Format = "jp2"
	JPEGXL   Format = "jxl"
	SVG      Format = "svg"
)

func ParseExtension

func ParseExtension(extension string) (Format, error)

ParseExtension is a filename convenience, never media validation.

func ParseMediaType

func ParseMediaType(media string) (Format, error)

ParseMediaType recognizes image media types. Recognition does not imply that a particular engine can read or write the format; consult its Capabilities.

func (Format) CanDecode

func (f Format) CanDecode() bool

CanDecode reports whether the portable engine can read this format.

func (Format) Extension

func (f Format) Extension() string

func (Format) MediaType

func (f Format) MediaType() string

func (Format) Validate

func (f Format) Validate() error

type FormatCapability

type FormatCapability struct {
	Format                        Format
	Read, Write                   bool
	ReadAnimation, WriteAnimation bool
	// WriteMetadata reports a native writer with verified ICC round-trip support.
	// Other metadata families are retained where that format supports them.
	WriteMetadata bool
}

FormatCapability distinguishes reading, writing and animation support. A recognized format need not support every operation.

type Frames

type Frames uint8
const (
	RejectAnimation Frames = iota
	FirstFrame
	PreserveAnimation
)

type Info

type Info struct {
	Format                Format
	Width, Height, Images int
	Animated              bool
	Orientation           uint8
}

Info is inspected container information, not proof that compressed pixels are valid. Process performs full decoding of the selected image. Images counts frames, TIFF pages or ICO representations; only animation sets Animated.

func Inspect

func Inspect(data []byte, limits Limits) (Info, error)

Inspect does no pixel decode and never consults filename or supplied MIME. Input must remain unchanged for the duration of this synchronous call.

type Limits

type Limits struct {
	InputBytes, OutputBytes int64
	Width, Height           int
	Pixels                  int64
	Frames                  int
	WorkingBytes            int64
}

Limits apply before pixel decoding, before each transform, and to output. WorkingBytes bounds the admitted workspace of each pipeline phase: the retained encoded input plus the pixel buffers live in that phase (decoder buffers, each transform's input, output and scratch, and the encoder's working copies with the owned output allowance). Per-pixel costs come from measurements of the engine's codecs (see the imaging guide). It is not a process heap or OS memory quota; codec/runtime bookkeeping and garbage collection are separate. There is deliberately no unbounded input option.

func DefaultLimits

func DefaultLimits() Limits

func (Limits) Validate

func (l Limits) Validate() error

type MaskMode

type MaskMode uint8
const (
	AlphaMask MaskMode = iota
	LuminanceMask
)

type Metadata

type Metadata uint8

Metadata selects retention after transformation. The default strips metadata. Preservation requires an available libvips runtime and an output with WriteMetadata support. PreserveMetadata includes EXIF (including GPS), XMP, IPTC and ICC where supported; obsolete EXIF orientation, dimensions and thumbnails are normalized on output.

const (
	StripMetadata Metadata = iota
	PreserveMetadata
	PreserveColorProfile
)

type MissingGlyph

type MissingGlyph uint8
const (
	RejectMissingGlyph MissingGlyph = iota
	ReplaceMissingGlyph
)

type Orientation

type Orientation uint8
const (
	ApplyOrientation Orientation = iota
	IgnoreOrientation
)

type PNGCompression

type PNGCompression uint8

PNGCompression selects a lossless PNG/APNG compression effort. Compression changes encoding time and file size, never the represented pixel values.

const (
	PNGDefaultCompression PNGCompression = iota
	PNGNoCompression
	PNGBestSpeed
	PNGBestCompression
)

type Path

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

Path is immutable. Each builder returns an independent path. Closed contours use nonzero winding; reverse an inner contour's direction to make a hole.

func NewPath

func NewPath() Path

func (Path) Close

func (p Path) Close() Path

func (Path) CubicTo

func (p Path) CubicTo(cx1, cy1, cx2, cy2, x, y float64) Path

func (Path) LineTo

func (p Path) LineTo(x, y float64) Path

func (Path) MoveTo

func (p Path) MoveTo(x, y float64) Path

func (Path) QuadraticTo

func (p Path) QuadraticTo(cx, cy, x, y float64) Path

func (Path) Validate

func (p Path) Validate() error

type Placement

type Placement struct {
	Position Position
	X, Y     int
	Opacity  value.Optional[float64]
	Blend    BlendMode
}

Placement positions a layer relative to the canvas. Positive offsets move right/down, including at right/bottom anchors; use negative offsets for inset. Omitted opacity is 1; an explicitly supplied zero is fully transparent.

func (Placement) Validate

func (p Placement) Validate() error

type Plan

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

Plan holds copied values and immutable image results, never callbacks or caller-owned mutable image buffers. Methods return independent plans; a zero plan has no transforms and keeps the detected format. Quality applies only to JPEG, including a detected JPEG.

func NewPlan

func NewPlan() Plan

func (Plan) AVIFAlphaQuality

func (p Plan) AVIFAlphaQuality(quality int) Plan

AVIFAlphaQuality sets alpha quality independently to 1..100; by default it follows AVIFQuality. Requires an explicit AVIF output.

func (Plan) AVIFQuality

func (p Plan) AVIFQuality(q int) Plan

AVIFQuality selects AVIF quality 1..100 (100 uses the lowest quantizer). RGB conversion and chroma subsampling still apply; it requires an explicit AVIF output. The default is DefaultAVIFQuality.

func (Plan) AVIFSpeed

func (p Plan) AVIFSpeed(speed int) Plan

AVIFSpeed selects encoding speed 0..10, from most thorough to fastest search. The default is DefaultAVIFSpeed. Requires an explicit AVIF output. A slow synchronous encode retains engine capacity until it actually exits.

func (Plan) Background

func (p Plan) Background(c color.NRGBA) Plan

Background flattens the result over an opaque color before encoding, so a format without alpha (JPEG) does not render transparent pixels as black. It applies to every output format when set.

func (Plan) Blur

func (p Plan) Blur(sigma float64) Plan

func (Plan) Brightness

func (p Plan) Brightness(offset int) Plan

Brightness adds an 8-bit channel offset, preserving alpha.

func (Plan) Canvas

func (p Plan) Canvas(width, height int, background color.NRGBA, position Position) Plan

Canvas changes the canvas without resampling, clipping or extending around the anchor. background fills new pixels and may be transparent.

func (Plan) CanvasRelative

func (p Plan) CanvasRelative(width, height int, background color.NRGBA, position Position) Plan

CanvasRelative adds signed deltas to the current canvas size.

func (Plan) Circle

func (p Plan) Circle(x, y, radius float64, style ShapeStyle) Plan

func (Plan) Contain

func (p Plan) Contain(width, height int, background color.NRGBA, position Position) Plan

Contain is Pad with enlargement enabled.

func (Plan) Contrast

func (p Plan) Contrast(value float64) Plan

Contrast applies the reference framework's squared (100+value)/100 factor around the channel midpoint. Values outside [-100,100] are rejected.

func (Plan) Crop

func (p Plan) Crop(x, y, width, height int) Plan

func (Plan) CropAt

func (p Plan) CropAt(width, height int, position Position) Plan

CropAt takes a positioned rectangle without resampling. It must fit inside the input; use Canvas to extend the image instead.

func (Plan) Draw

func (p Plan) Draw(path Path, style ShapeStyle) Plan

Draw adds an antialiased vector path. Open contours are closed for filling; strokes close only contours with an explicit Close command.

func (Plan) Ellipse

func (p Plan) Ellipse(x, y, radiusX, radiusY float64, style ShapeStyle) Plan

Ellipse uses a center and positive horizontal/vertical radii.

func (Plan) Fill

func (p Plan) Fill(width, height int, upscale bool) Plan

func (Plan) FillAt

func (p Plan) FillAt(width, height int, upscale bool, position Position) Plan

FillAt resizes to cover the target and crops at position. A target requiring enlargement fails when upscale is false, just as with Fill.

func (Plan) Fit

func (p Plan) Fit(width, height int, upscale bool) Plan

func (Plan) FitHeight

func (p Plan) FitHeight(height int, upscale bool) Plan

FitHeight preserves the aspect ratio while targeting one height.

func (Plan) FitWidth

func (p Plan) FitWidth(width int, upscale bool) Plan

FitWidth preserves the aspect ratio while targeting one width.

func (Plan) FlipHorizontal

func (p Plan) FlipHorizontal() Plan

func (Plan) FlipVertical

func (p Plan) FlipVertical() Plan

func (Plan) Format

func (p Plan) Format(f Format) Plan

func (Plan) Frames

func (p Plan) Frames(f Frames) Plan

func (Plan) Gamma

func (p Plan) Gamma(value float64) Plan

Gamma applies gamma correction. Values above one lighten; below one darken.

func (Plan) GoString

func (Plan) GoString() string

func (Plan) Grayscale

func (p Plan) Grayscale() Plan

func (Plan) HEIFQuality

func (p Plan) HEIFQuality(quality int) Plan

HEIFQuality selects HEVC quality 1..100, default 85. Requires explicit HEIF output and an available libvips runtime. A quality of 100 is not a lossless guarantee.

func (Plan) Hue

func (p Plan) Hue(degrees float64) Plan

Hue shifts hue by degrees in [-360,360].

func (Plan) Insert

func (p Plan) Insert(layer Result, placement Placement) Plan

Insert composites an immutable processed Result onto this image. Prepare the layer once with Engine.Process, then reuse it in concurrent plans. Pixels outside the canvas are clipped; layer bytes and decoding count toward limits.

func (Plan) Invert

func (p Plan) Invert() Plan

Invert reverses RGB channels, preserving alpha.

func (Plan) JPEG2000Quality

func (p Plan) JPEG2000Quality(quality int) Plan

JPEG2000Quality selects lossy quality 1..100 for explicit JPEG2000 output. Omitting it keeps the default lossless encoding. Requires an available libvips runtime.

func (Plan) JPEGQuality

func (p Plan) JPEGQuality(q int) Plan

func (Plan) JPEGXLQuality

func (p Plan) JPEGXLQuality(quality int) Plan

JPEGXLQuality selects lossy quality 1..100 for explicit JPEGXL output. Omitting it keeps the default lossless encoding. Requires an available libvips runtime.

func (Plan) Line

func (p Plan) Line(x1, y1, x2, y2, width float64, c color.NRGBA) Plan

func (Plan) Mask

func (p Plan) Mask(layer Result, placement Placement, mode MaskMode) Plan

Mask multiplies existing alpha by mask alpha, and for LuminanceMask also by weighted RGB luminance. Pixels outside the positioned mask become transparent. Placement opacity is supported; blend modes other than BlendNormal reject.

func (Plan) Metadata

func (p Plan) Metadata(m Metadata) Plan

func (Plan) Orientation

func (p Plan) Orientation(o Orientation) Plan

func (Plan) PNGCompression

func (p Plan) PNGCompression(compression PNGCompression) Plan

PNGCompression selects compression for every encoded PNG/APNG frame. It requires an explicit PNG output, including PNGDefaultCompression.

func (Plan) Pad

func (p Plan) Pad(width, height int, background color.NRGBA, position Position) Plan

Pad fits without enlargement into an exact canvas and fills unused pixels. background may be transparent.

func (Plan) Pixelate

func (p Plan) Pixelate(size int) Plan

Pixelate replaces square blocks with their average color.

func (Plan) Polygon

func (p Plan) Polygon(points []Point, style ShapeStyle) Plan

Polygon snapshots points. At least three points are required.

func (Plan) Rectangle

func (p Plan) Rectangle(x, y, width, height float64, style ShapeStyle) Plan

func (Plan) Resampling

func (p Plan) Resampling(r Resampling) Plan

func (Plan) Resize

func (p Plan) Resize(width, height int) Plan

func (Plan) ResizeDown

func (p Plan) ResizeDown(width, height int) Plan

ResizeDown resizes each axis independently, without enlarging either axis.

func (Plan) Rotate

func (p Plan) Rotate(r Rotation) Plan

func (Plan) RotateDegrees

func (p Plan) RotateDegrees(degrees float64, background color.NRGBA) Plan

RotateDegrees rotates clockwise, expanding the canvas to contain the image. Angles are finite in [-360,360]. Cubic interpolation is used, except exact quarter-turns, which retain pixels without interpolation.

func (Plan) Saturation

func (p Plan) Saturation(percentage float64) Plan

Saturation changes saturation by a percentage in [-100,100].

func (Plan) Sepia

func (p Plan) Sepia(percentage float64) Plan

Sepia applies a sepia effect with strength in [0,100].

func (Plan) Sharpen

func (p Plan) Sharpen(sigma, amount, threshold float64) Plan

Sharpen applies an unsharp mask. Sigma is in (0,100], amount in [0,10], threshold in [0,1]. Typical values are (1, 1, 0.02).

func (Plan) SmartFill

func (p Plan) SmartFill(width, height int, upscale bool, interest CropInterest) Plan

SmartFill resizes to cover the requested canvas and selects a crop using visual attention or entropy. Requires an available libvips runtime. Like Fill, it rejects an insufficient source size when upscale is false.

func (Plan) String

func (Plan) String() string

String and GoString redact prepared layer bytes from routine/debug formatting. Format is already the fluent output-format method, so Plan is not a Formatter.

func (Plan) Text

func (p Plan) Text(text string, options TextOptions) Plan

Text draws antialiased outline glyphs with kerning. Font assets and the text are owned by the immutable plan. This renderer lays out left-to-right glyphs; it does not perform bidirectional layout, script shaping or color emoji.

func (Plan) Threshold

func (p Plan) Threshold(percentage float64) Plan

Threshold makes RGB black or white using a luminance percentage in [0,100].

func (Plan) ToSRGB

func (p Plan) ToSRGB() Plan

ToSRGB converts an embedded ICC profile to 8-bit sRGB before applying the plan. Images without a profile use their declared color interpretation. Requires an available libvips runtime; malformed profiles fail instead of being ignored.

func (Plan) Validate

func (p Plan) Validate() error

func (Plan) WebPMethod

func (p Plan) WebPMethod(method int) Plan

WebPMethod selects search effort 0..6 (fastest to most thorough), default DefaultWebPMethod. Explicit zero is preserved. Applies to either WebP mode.

func (Plan) WebPMode

func (p Plan) WebPMode(mode WebPMode) Plan

WebPMode selects WebPLossless (the default) or WebPLossy. Requires explicit WebP output. Lossless preserves the RGB of fully transparent pixels too.

func (Plan) WebPQuality

func (p Plan) WebPQuality(quality int) Plan

WebPQuality selects lossy color quality 1..100, default DefaultWebPQuality. Requires explicit WebP output and WebPLossy mode; 100 is still lossy.

type Point

type Point struct{ X, Y float64 }

Drawing coordinates are measured in pixels from the top-left canvas corner. Finite coordinates in [-65535,65535] are accepted and clipped to the canvas.

type Position

type Position uint8

Position anchors an image or crop rectangle. The zero value is Center.

const (
	Center Position = iota
	TopLeft
	Top
	TopRight
	Left
	Right
	BottomLeft
	Bottom
	BottomRight
)

type Resampling

type Resampling uint8

Resampling selects the reconstruction filter used by every resize in a plan. Lanczos is the default. NearestNeighbor is useful for pixel art.

const (
	Lanczos Resampling = iota
	Cubic
	Linear
	Box
	NearestNeighbor
)

type Result

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

Result owns encoded output. Reader exposes read-only access; Bytes returns an independent copy. Routine formatting never exports image bytes.

func (Result) Bytes

func (r Result) Bytes() []byte

func (Result) Format

func (Result) Format(s fmt.State, _ rune)

func (Result) Info

func (r Result) Info() Info

func (Result) MarshalJSON

func (Result) MarshalJSON() ([]byte, error)

func (Result) Reader

func (r Result) Reader() io.Reader

func (Result) Size

func (r Result) Size() int64

type Rotation

type Rotation uint16
const (
	Rotate90  Rotation = 90
	Rotate180 Rotation = 180
	Rotate270 Rotation = 270
)

type ShapeStyle

type ShapeStyle struct {
	Fill        color.NRGBA
	Stroke      color.NRGBA
	StrokeWidth float64
}

ShapeStyle draws the fill first, then a centered stroke with round joins and round caps. Transparent colors and a zero stroke width disable that paint.

func (ShapeStyle) Validate

func (s ShapeStyle) Validate() error

type TextAlignment

type TextAlignment uint8
const (
	AlignLeft TextAlignment = iota
	AlignCenter
	AlignRight
)

type TextOptions

type TextOptions struct {
	Font         Font
	Size         float64
	Color        color.NRGBA
	Position     Position
	X, Y         int
	MaxWidth     int
	Align        TextAlignment
	LineHeight   float64
	MissingGlyph MissingGlyph
}

TextOptions positions a block of line boxes, with the first baseline one font ascent below its top. Size is pixels per em (1..512). MaxWidth wraps at spaces, splitting long words when necessary; zero disables wrapping. Explicit newlines are preserved, CRLF is normalized, and tabs become four spaces. LineHeight is a size multiplier (0.5..4); zero selects 1.2. Align applies within MaxWidth, or within the longest line when MaxWidth is zero.

func (TextOptions) Validate

func (o TextOptions) Validate() error

type WebPMode

type WebPMode uint8

WebPMode selects exact lossless pixels or lossy 4:2:0 color compression. Alpha remains lossless in both modes.

const (
	WebPLossless WebPMode = iota
	WebPLossy
)

Jump to

Keyboard shortcuts

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