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
- Variables
- func Module(name foundation.ProviderID, key foundation.Key[*Engine], config Config) foundation.Module
- type Backend
- type BlendMode
- type Capabilities
- type Config
- type CropInterest
- type Engine
- func (e *Engine) Capabilities() Capabilities
- func (e *Engine) Close(ctx context.Context) error
- func (e *Engine) Create(ctx context.Context, width, height int, background color.NRGBA, plan Plan) (Result, error)
- func (e *Engine) Done() <-chan struct{}
- func (*Engine) Format(s fmt.State, _ rune)
- func (e *Engine) Inspect(ctx context.Context, data []byte) (Info, error)
- func (e *Engine) Limits() Limits
- func (e *Engine) NativeError() error
- func (e *Engine) Process(ctx context.Context, source io.Reader, plan Plan) (Result, error)
- func (e *Engine) ProcessBytes(ctx context.Context, data []byte, plan Plan) (Result, error)
- func (e *Engine) Validate() error
- func (e *Engine) ValidatePlan(p Plan) error
- type Font
- type FontStyle
- type Format
- type FormatCapability
- type Frames
- type Info
- type Limits
- type MaskMode
- type Metadata
- type MissingGlyph
- type Orientation
- type PNGCompression
- type Path
- type Placement
- type Plan
- func (p Plan) AVIFAlphaQuality(quality int) Plan
- func (p Plan) AVIFQuality(q int) Plan
- func (p Plan) AVIFSpeed(speed int) Plan
- func (p Plan) Background(c color.NRGBA) Plan
- func (p Plan) Blur(sigma float64) Plan
- func (p Plan) Brightness(offset int) Plan
- func (p Plan) Canvas(width, height int, background color.NRGBA, position Position) Plan
- func (p Plan) CanvasRelative(width, height int, background color.NRGBA, position Position) Plan
- func (p Plan) Circle(x, y, radius float64, style ShapeStyle) Plan
- func (p Plan) Contain(width, height int, background color.NRGBA, position Position) Plan
- func (p Plan) Contrast(value float64) Plan
- func (p Plan) Crop(x, y, width, height int) Plan
- func (p Plan) CropAt(width, height int, position Position) Plan
- func (p Plan) Draw(path Path, style ShapeStyle) Plan
- func (p Plan) Ellipse(x, y, radiusX, radiusY float64, style ShapeStyle) Plan
- func (p Plan) Fill(width, height int, upscale bool) Plan
- func (p Plan) FillAt(width, height int, upscale bool, position Position) Plan
- func (p Plan) Fit(width, height int, upscale bool) Plan
- func (p Plan) FitHeight(height int, upscale bool) Plan
- func (p Plan) FitWidth(width int, upscale bool) Plan
- func (p Plan) FlipHorizontal() Plan
- func (p Plan) FlipVertical() Plan
- func (p Plan) Format(f Format) Plan
- func (p Plan) Frames(f Frames) Plan
- func (p Plan) Gamma(value float64) Plan
- func (Plan) GoString() string
- func (p Plan) Grayscale() Plan
- func (p Plan) HEIFQuality(quality int) Plan
- func (p Plan) Hue(degrees float64) Plan
- func (p Plan) Insert(layer Result, placement Placement) Plan
- func (p Plan) Invert() Plan
- func (p Plan) JPEG2000Quality(quality int) Plan
- func (p Plan) JPEGQuality(q int) Plan
- func (p Plan) JPEGXLQuality(quality int) Plan
- func (p Plan) Line(x1, y1, x2, y2, width float64, c color.NRGBA) Plan
- func (p Plan) Mask(layer Result, placement Placement, mode MaskMode) Plan
- func (p Plan) Metadata(m Metadata) Plan
- func (p Plan) Orientation(o Orientation) Plan
- func (p Plan) PNGCompression(compression PNGCompression) Plan
- func (p Plan) Pad(width, height int, background color.NRGBA, position Position) Plan
- func (p Plan) Pixelate(size int) Plan
- func (p Plan) Polygon(points []Point, style ShapeStyle) Plan
- func (p Plan) Rectangle(x, y, width, height float64, style ShapeStyle) Plan
- func (p Plan) Resampling(r Resampling) Plan
- func (p Plan) Resize(width, height int) Plan
- func (p Plan) ResizeDown(width, height int) Plan
- func (p Plan) Rotate(r Rotation) Plan
- func (p Plan) RotateDegrees(degrees float64, background color.NRGBA) Plan
- func (p Plan) Saturation(percentage float64) Plan
- func (p Plan) Sepia(percentage float64) Plan
- func (p Plan) Sharpen(sigma, amount, threshold float64) Plan
- func (p Plan) SmartFill(width, height int, upscale bool, interest CropInterest) Plan
- func (Plan) String() string
- func (p Plan) Text(text string, options TextOptions) Plan
- func (p Plan) Threshold(percentage float64) Plan
- func (p Plan) ToSRGB() Plan
- func (p Plan) Validate() error
- func (p Plan) WebPMethod(method int) Plan
- func (p Plan) WebPMode(mode WebPMode) Plan
- func (p Plan) WebPQuality(quality int) Plan
- type Point
- type Position
- type Resampling
- type Result
- type Rotation
- type ShapeStyle
- type TextAlignment
- type TextOptions
- type WebPMode
Constants ¶
const DefaultAVIFQuality = 60
DefaultAVIFQuality is used unless a plan selects AVIFQuality.
const DefaultAVIFSpeed = 10
DefaultAVIFSpeed favors fast encoding. Zero, when explicitly selected with AVIFSpeed, requests the most thorough search; it is not an omitted setting.
const DefaultWebPMethod = 4
const DefaultWebPQuality = 75
const MaxFontBytes = 8 << 20
const MaxPathCommands = 1024
const (
MaxTextRunes = 4096
)
const MaxTransforms = 32
Variables ¶
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.
type BlendMode ¶
type BlendMode uint8
BlendMode combines straight RGB channels before source-over alpha composition.
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)
ForFormat returns the capability for format and whether it was found.
type Config ¶
Config sets codec discovery, resource limits, admission capacity and operation timeout.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns automatic codec discovery, default limits, two active calls and a one-minute timeout.
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 (*Engine) Capabilities ¶
func (e *Engine) Capabilities() Capabilities
Capabilities returns an owned snapshot, or an empty snapshot for an invalid engine.
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{}
Done closes after the engine closes and all admitted work exits.
func (*Engine) Inspect ¶
Inspect examines input with this engine's codecs, limits and admission owner. The package-level Inspect function always uses portable codecs.
func (*Engine) NativeError ¶
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 ¶
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 ¶
ProcessBytes runs the same bounded pipeline directly on data without copying it. data must not change during the call.
func (*Engine) ValidatePlan ¶
ValidatePlan checks the plan and rejects features unavailable in this engine.
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 ¶
BuiltinFont loads one of the Go fonts already included with Foundry. Apps need no font download, filesystem path or additional Go dependency.
func ParseFont ¶
ParseFont copies data before parsing. Collections, WOFF and bitmap/color fonts are not supported by this portable outline renderer.
type Format ¶
type Format string
Format identifies an image encoding or container.
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 ¶
ParseExtension is a filename convenience, never media validation.
func ParseMediaType ¶
ParseMediaType recognizes image media types. Recognition does not imply that a particular engine can read or write the format; consult its Capabilities.
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
Frames selects whether animation is rejected, reduced to its first frame or preserved.
type Info ¶
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.
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
DefaultLimits returns the default input, output, dimension, frame and workspace bounds.
type MaskMode ¶
type MaskMode uint8
MaskMode selects alpha-only or luminance-weighted mask coverage.
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.
type MissingGlyph ¶
type MissingGlyph uint8
MissingGlyph selects whether unavailable glyphs fail or use the font missing-glyph outline.
const ( RejectMissingGlyph MissingGlyph = iota ReplaceMissingGlyph )
type Orientation ¶
type Orientation uint8
Orientation selects whether input orientation metadata is applied or ignored.
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
NewPath returns an empty path; add drawing commands before validating or rendering it.
func (Path) CubicTo ¶
CubicTo returns a path with a cubic curve using two control points and an endpoint.
func (Path) QuadraticTo ¶
QuadraticTo returns a path with a quadratic curve using a control point and an endpoint.
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.
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
NewPlan returns a zero plan with no transforms and the detected input format.
func (Plan) AVIFAlphaQuality ¶
AVIFAlphaQuality sets alpha quality independently to 1..100; by default it follows AVIFQuality. Requires an explicit AVIF output.
func (Plan) AVIFQuality ¶
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 ¶
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 ¶
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) Brightness ¶
Brightness adds an 8-bit channel offset, preserving alpha.
func (Plan) Canvas ¶
Canvas changes the canvas without resampling, clipping or extending around the anchor. background fills new pixels and may be transparent.
func (Plan) CanvasRelative ¶
CanvasRelative adds signed deltas to the current canvas size.
func (Plan) Circle ¶
func (p Plan) Circle(x, y, radius float64, style ShapeStyle) Plan
Circle returns a plan drawing a circle with the supplied center, positive radius and style.
func (Plan) Contrast ¶
Contrast applies the reference framework's squared (100+value)/100 factor around the channel midpoint. Values outside [-100,100] are rejected.
func (Plan) CropAt ¶
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 ¶
Fill returns a plan resizing to cover the dimensions and cropping at the center; insufficient source size fails when upscale is false.
func (Plan) FillAt ¶
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 ¶
Fit returns a plan resizing proportionally within the dimensions, allowing enlargement only when upscale is true.
func (Plan) FlipHorizontal ¶
FlipHorizontal returns a plan mirroring pixels horizontally.
func (Plan) FlipVertical ¶
FlipVertical returns a plan mirroring pixels vertically.
func (Plan) HEIFQuality ¶
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) Insert ¶
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) JPEG2000Quality ¶
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 ¶
JPEGQuality returns a plan with JPEG quality; zero selects the default quality.
func (Plan) JPEGXLQuality ¶
JPEGXLQuality selects lossy quality 1..100 for explicit JPEGXL output. Omitting it keeps the default lossless encoding. Requires an available libvips runtime.
func (Plan) Mask ¶
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) Orientation ¶
func (p Plan) Orientation(o Orientation) Plan
Orientation returns a plan with the selected input orientation policy.
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 ¶
Pad fits without enlargement into an exact canvas and fills unused pixels. background may be transparent.
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
Rectangle returns a plan drawing a rectangle from its top-left corner with positive dimensions.
func (Plan) Resampling ¶
func (p Plan) Resampling(r Resampling) Plan
Resampling returns a plan using the selected filter for resize operations.
func (Plan) Resize ¶
Resize returns a plan resizing exactly to the dimensions, allowing enlargement.
func (Plan) ResizeDown ¶
ResizeDown resizes each axis independently, without enlarging either axis.
func (Plan) RotateDegrees ¶
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 ¶
Saturation changes saturation by a percentage in [-100,100].
func (Plan) Sharpen ¶
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 ¶
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) ToSRGB ¶
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 ¶
Validate rejects invalid settings and transforms with an invalid fault; it does not inspect input pixels.
func (Plan) WebPMethod ¶
WebPMethod selects search effort 0..6 (fastest to most thorough), default DefaultWebPMethod. Explicit zero is preserved. Applies to either WebP mode.
func (Plan) WebPMode ¶
WebPMode selects WebPLossless (the default) or WebPLossy. Requires explicit WebP output. Lossless preserves the RGB of fully transparent pixels too.
func (Plan) WebPQuality ¶
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.
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) MarshalJSON ¶
MarshalJSON rejects implicit byte export with an invalid fault.
type ShapeStyle ¶
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
Validate rejects nonfinite, negative or excessive stroke widths with an invalid fault.
type TextAlignment ¶
type TextAlignment uint8
TextAlignment selects horizontal alignment within the text block.
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
Validate rejects an unloaded font or invalid text layout settings with an invalid fault.
Source Files
¶
- animation.go
- avif_container.go
- avif_decode.go
- avif_items.go
- avif_sequence.go
- backend.go
- capabilities.go
- composite.go
- create.go
- drawing.go
- effects.go
- encoding.go
- engine.go
- font.go
- format.go
- geometry.go
- icon.go
- inspect.go
- limits.go
- module.go
- native_callbacks.go
- native_encoding.go
- native_input.go
- native_vips.go
- orientation.go
- path.go
- plan.go
- png_animation.go
- png_container.go
- text.go
- transform.go
- webp_animation.go
- webp_color.go
- webp_container.go
- webp_decode.go
- webp_output.go