Documentation
¶
Overview ¶
Package image provides image buffer management for gogpu/gg.
Package image provides image buffer management for gogpu/gg.
This package implements enterprise-grade image handling with support for multiple pixel formats, lazy premultiplication, and memory-efficient operations.
Package image provides image buffer management for gogpu/gg.
Package image provides image buffer management for gogpu/gg.
This package implements enterprise-grade image handling with support for multiple pixel formats, lazy premultiplication, and memory-efficient operations.
Package image provides image buffer management for gogpu/gg.
Package image provides image buffer management for gogpu/gg.
Package image provides image buffer management for gogpu/gg.
Package image provides image buffer management for gogpu/gg.
Index ¶
- Variables
- func DrawImage(dst, src *ImageBuf, params DrawParams)
- func PutToDefault(buf *ImageBuf)
- func Sample(img *ImageBuf, u, v float64, mode InterpolationMode) (r, g, b, a byte)
- func SampleBicubic(img *ImageBuf, u, v float64) (r, g, b, a byte)
- func SampleBilinear(img *ImageBuf, u, v float64) (r, g, b, a byte)
- func SampleNearest(img *ImageBuf, u, v float64) (r, g, b, a byte)
- type Affine
- type BlendMode
- type DrawParams
- type Format
- func (f Format) BitsPerChannel() int
- func (f Format) BytesPerPixel() int
- func (f Format) Channels() int
- func (f Format) HasAlpha() bool
- func (f Format) ImageBytes(width, height int) int
- func (f Format) Info() FormatInfo
- func (f Format) IsGrayscale() bool
- func (f Format) IsPremultiplied() bool
- func (f Format) IsValid() bool
- func (f Format) PremultipliedVersion() Format
- func (f Format) RowBytes(width int) int
- func (f Format) String() string
- func (f Format) UnpremultipliedVersion() Format
- type FormatInfo
- type ImageBuf
- func Decode(r io.Reader) (*ImageBuf, error)
- func DecodeJPEG(r io.Reader) (*ImageBuf, error)
- func DecodePNG(r io.Reader) (*ImageBuf, error)
- func DecodeWebP(r io.Reader) (*ImageBuf, error)
- func FromRaw(data []byte, width, height int, format Format, stride int) (*ImageBuf, error)
- func FromStdImage(img image.Image) *ImageBuf
- func GetFromDefault(width, height int, format Format) *ImageBuf
- func LoadImage(path string) (*ImageBuf, error)
- func LoadImageFromBytes(data []byte) (*ImageBuf, error)
- func LoadJPEG(path string) (*ImageBuf, error)
- func LoadPNG(path string) (*ImageBuf, error)
- func LoadWebP(path string) (*ImageBuf, error)
- func NewImageBuf(width, height int, format Format) (*ImageBuf, error)
- func NewImageBufWithStride(width, height int, format Format, stride int) (*ImageBuf, error)
- func (b *ImageBuf) Bounds() (int, int)
- func (b *ImageBuf) ByteSize() int
- func (b *ImageBuf) Clear()
- func (b *ImageBuf) Clone() *ImageBuf
- func (b *ImageBuf) Data() []byte
- func (b *ImageBuf) EncodeJPEG(w io.Writer, quality int) error
- func (b *ImageBuf) EncodePNG(w io.Writer) error
- func (b *ImageBuf) EncodeToBytes() ([]byte, error)
- func (b *ImageBuf) EncodeToJPEGBytes(quality int) ([]byte, error)
- func (b *ImageBuf) Fill(r, g, bl, a uint8)
- func (b *ImageBuf) Format() Format
- func (b *ImageBuf) GetRGBA(x, y int) (r, g, bl, a uint8)
- func (b *ImageBuf) Height() int
- func (b *ImageBuf) InvalidatePremulCache()
- func (b *ImageBuf) IsEmpty() bool
- func (b *ImageBuf) IsPremulCached() bool
- func (b *ImageBuf) PixelBytes(x, y int) []byte
- func (b *ImageBuf) PixelOffset(x, y int) int
- func (b *ImageBuf) PremultipliedData() []byte
- func (b *ImageBuf) RowBytes(y int) []byte
- func (b *ImageBuf) SaveJPEG(path string, quality int) error
- func (b *ImageBuf) SavePNG(path string) error
- func (b *ImageBuf) SetPixelBytes(x, y int, pixel []byte) error
- func (b *ImageBuf) SetRGBA(x, y int, r, g, bl, a uint8) error
- func (b *ImageBuf) Stride() int
- func (b *ImageBuf) SubImage(x, y, width, height int) *ImageBuf
- func (b *ImageBuf) ToStdImage() image.Image
- func (b *ImageBuf) Width() int
- type ImagePattern
- func (p *ImagePattern) Image() *ImageBuf
- func (p *ImagePattern) Interpolation() InterpolationMode
- func (p *ImagePattern) Mipmaps() *MipmapChain
- func (p *ImagePattern) Opacity() float64
- func (p *ImagePattern) Sample(x, y float64) (r, g, b, a byte)
- func (p *ImagePattern) SampleWithScale(x, y, scale float64) (r, g, b, a byte)
- func (p *ImagePattern) SpreadMode() SpreadMode
- func (p *ImagePattern) Transform() Affine
- func (p *ImagePattern) WithInterpolation(mode InterpolationMode) *ImagePattern
- func (p *ImagePattern) WithMipmaps(chain *MipmapChain) *ImagePattern
- func (p *ImagePattern) WithOpacity(opacity float64) *ImagePattern
- func (p *ImagePattern) WithSpreadMode(mode SpreadMode) *ImagePattern
- func (p *ImagePattern) WithTransform(t Affine) *ImagePattern
- type InterpolationMode
- type MipmapChain
- type Pool
- type Rect
- type SpreadMode
Constants ¶
This section is empty.
Variables ¶
var ( // ErrInvalidDimensions is returned when width or height is non-positive. ErrInvalidDimensions = errors.New("image: invalid dimensions") // ErrInvalidFormat is returned when the format is not recognized. ErrInvalidFormat = errors.New("image: invalid format") // ErrInvalidStride is returned when stride is less than minimum required. ErrInvalidStride = errors.New("image: stride too small for width") // ErrDataTooSmall is returned when provided data is smaller than required. ErrDataTooSmall = errors.New("image: data buffer too small") // ErrOutOfBounds is returned when pixel coordinates are outside image bounds. ErrOutOfBounds = errors.New("image: coordinates out of bounds") )
Common errors for image operations.
var ( // ErrUnsupportedFormat is returned when the image format is not supported. ErrUnsupportedFormat = errors.New("image: unsupported format") // ErrEmptyData is returned when image data is empty. ErrEmptyData = errors.New("image: empty data") )
I/O errors.
Functions ¶
func DrawImage ¶
func DrawImage(dst, src *ImageBuf, params DrawParams)
DrawImage draws the source image onto the destination image using the specified parameters.
The operation performs the following steps:
- For each pixel in the destination rectangle
- Apply inverse transformation to find source coordinates
- Sample source image using specified interpolation
- Apply opacity to the sampled color
- Blend with destination using specified blend mode
The destination image is modified in place.
func PutToDefault ¶
func PutToDefault(buf *ImageBuf)
PutToDefault returns an image buffer to the default pool. This is a convenience wrapper around defaultPool.Put().
func Sample ¶
func Sample(img *ImageBuf, u, v float64, mode InterpolationMode) (r, g, b, a byte)
Sample samples the image at normalized coordinates (u, v) using the specified interpolation mode. u and v are in the range [0.0, 1.0] where (0,0) is top-left and (1,1) is bottom-right. Out-of-bounds coordinates are clamped to the edge.
func SampleBicubic ¶
SampleBicubic performs bicubic interpolation at normalized coordinates (u, v). Uses Catmull-Rom splines with a 4x4 pixel neighborhood for smooth results.
func SampleBilinear ¶
SampleBilinear performs bilinear interpolation at normalized coordinates (u, v). Interpolates between 4 neighboring pixels using linear weights.
func SampleNearest ¶
SampleNearest performs nearest-neighbor sampling at normalized coordinates (u, v). This is the fastest sampling method but produces blocky results when scaling.
Types ¶
type Affine ¶
type Affine struct {
// contains filtered or unexported fields
}
Affine represents a 2D affine transformation matrix.
The transformation is represented as a 3x3 matrix:
| a b c | | d e f | | 0 0 1 |
This allows for translation, rotation, scaling, and shearing operations.
func Rotate ¶
Rotate returns a rotation transformation that rotates by angle (in radians) around the origin. Positive angles rotate counter-clockwise.
func RotateAt ¶
RotateAt returns a rotation transformation that rotates by angle (in radians) around the point (cx, cy).
func Scale ¶
Scale returns a scaling transformation that scales by (sx, sy) around the origin. Use negative values to flip the image.
func ScaleAt ¶
ScaleAt returns a scaling transformation that scales by (sx, sy) around the point (cx, cy).
func Shear ¶
Shear returns a shearing transformation that shears by (sx, sy). sx controls horizontal shear (skew along x-axis). sy controls vertical shear (skew along y-axis).
func (Affine) Invert ¶
Invert returns the inverse transformation. Returns false if the matrix is singular (non-invertible).
type BlendMode ¶
type BlendMode uint8
BlendMode defines how source pixels are blended with destination pixels.
const ( // BlendNormal performs standard alpha blending (source over destination). BlendNormal BlendMode = iota // BlendMultiply multiplies source and destination colors. // Result is always darker or equal. Formula: dst * src BlendMultiply // BlendScreen performs inverse multiply for lighter results. // Formula: 1 - (1-dst) * (1-src) BlendScreen // BlendOverlay combines multiply and screen based on destination brightness. // Dark areas are multiplied, bright areas are screened. BlendOverlay )
type DrawParams ¶
type DrawParams struct {
// SrcRect defines the source rectangle to sample from.
// If nil, the entire source image is used.
SrcRect *Rect
// DstRect defines the destination rectangle to draw into.
DstRect Rect
// Transform is an optional affine transformation applied to source coordinates.
// If nil, identity transform is used.
Transform *Affine
// Interp specifies the interpolation mode for sampling.
Interp InterpolationMode
// Opacity controls the overall transparency of the source image (0.0 to 1.0).
// 1.0 means fully opaque, 0.0 means fully transparent.
Opacity float64
// BlendMode specifies how to blend source and destination pixels.
BlendMode BlendMode
}
DrawParams specifies parameters for the DrawImage operation.
type Format ¶
type Format uint8
Format represents a pixel storage format.
const ( // FormatGray8 is 8-bit grayscale (1 byte per pixel). FormatGray8 Format = iota // FormatGray16 is 16-bit grayscale (2 bytes per pixel). FormatGray16 // FormatRGB8 is 24-bit RGB (3 bytes per pixel, no alpha). FormatRGB8 // FormatRGBA8 is 32-bit RGBA in sRGB color space (4 bytes per pixel). // This is the standard format for most operations. FormatRGBA8 // FormatRGBAPremul is 32-bit RGBA with premultiplied alpha (4 bytes per pixel). // Used for correct alpha blending operations. FormatRGBAPremul // FormatBGRA8 is 32-bit BGRA in sRGB color space (4 bytes per pixel). // Common on Windows and some GPU formats. FormatBGRA8 // FormatBGRAPremul is 32-bit BGRA with premultiplied alpha (4 bytes per pixel). FormatBGRAPremul )
func (Format) BitsPerChannel ¶
BitsPerChannel returns the number of bits per color channel.
func (Format) BytesPerPixel ¶
BytesPerPixel returns the number of bytes per pixel for this format.
func (Format) ImageBytes ¶
ImageBytes calculates the total number of bytes needed for an image.
func (Format) IsGrayscale ¶
IsGrayscale returns true if this is a grayscale format.
func (Format) IsPremultiplied ¶
IsPremultiplied returns true if alpha is premultiplied.
func (Format) PremultipliedVersion ¶
PremultipliedVersion returns the premultiplied version of this format. Returns the same format if already premultiplied or has no alpha.
func (Format) RowBytes ¶
RowBytes calculates the number of bytes needed for a row of the given width.
func (Format) UnpremultipliedVersion ¶
UnpremultipliedVersion returns the non-premultiplied version of this format. Returns the same format if already non-premultiplied or has no alpha.
type FormatInfo ¶
type FormatInfo struct {
// BytesPerPixel is the number of bytes per pixel.
BytesPerPixel int
// Channels is the number of color channels.
Channels int
// HasAlpha indicates if the format has an alpha channel.
HasAlpha bool
// IsPremultiplied indicates if alpha is premultiplied.
IsPremultiplied bool
// IsGrayscale indicates if this is a grayscale format.
IsGrayscale bool
// BitsPerChannel is the number of bits per color channel.
BitsPerChannel int
}
FormatInfo contains metadata about a pixel format.
type ImageBuf ¶
type ImageBuf struct {
// contains filtered or unexported fields
}
ImageBuf is a memory-efficient image buffer with lazy premultiplication.
ImageBuf stores pixel data in a contiguous byte slice with optional stride for memory alignment. It supports lazy premultiplication - the premultiplied version is computed only when needed and cached for reuse.
Thread safety: ImageBuf is safe for concurrent read access. Write operations (Set*, Clear, InvalidatePremulCache) require external synchronization.
func DecodeJPEG ¶
DecodeJPEG decodes a JPEG image from the given reader.
func DecodeWebP ¶ added in v0.24.0
DecodeWebP decodes a WebP image from the given reader.
func FromRaw ¶
FromRaw creates an ImageBuf from existing data without copying. The caller must ensure data remains valid for the lifetime of the ImageBuf. Stride must be at least format.RowBytes(width).
func FromStdImage ¶
FromStdImage creates an ImageBuf from a standard library image.Image. The resulting ImageBuf will be in RGBA8 format.
func GetFromDefault ¶
GetFromDefault retrieves an image buffer from the default pool. This is a convenience wrapper around defaultPool.Get().
func LoadImage ¶
LoadImage loads an image from the given file path, auto-detecting the format. Supported formats: PNG, JPEG, WebP.
func LoadImageFromBytes ¶
LoadImageFromBytes loads an image from a byte slice, auto-detecting the format.
func NewImageBuf ¶
NewImageBuf creates a new image buffer with the given dimensions and format. Returns an error if dimensions are invalid or format is unknown.
func NewImageBufWithStride ¶
NewImageBufWithStride creates a new image buffer with custom stride for alignment. Stride must be at least format.RowBytes(width).
func (*ImageBuf) Clear ¶
func (b *ImageBuf) Clear()
Clear sets all pixels to zero (transparent black for RGBA formats).
func (*ImageBuf) Data ¶
Data returns the raw pixel data slice. Modifying this data will affect the image; call InvalidatePremulCache() after modifications if premultiplied data may have been cached.
func (*ImageBuf) EncodeJPEG ¶
EncodeJPEG encodes the image as JPEG to the given writer.
func (*ImageBuf) EncodeToBytes ¶
EncodeToBytes encodes the image to PNG format and returns the bytes.
func (*ImageBuf) EncodeToJPEGBytes ¶
EncodeToJPEGBytes encodes the image to JPEG format and returns the bytes.
func (*ImageBuf) GetRGBA ¶
GetRGBA returns the color at (x, y) as (r, g, b, a) in 0-255 range. For grayscale formats, r=g=b=gray and a=255. For formats without alpha, a=255. Returns (0,0,0,0) if coordinates are out of bounds.
func (*ImageBuf) InvalidatePremulCache ¶
func (b *ImageBuf) InvalidatePremulCache()
InvalidatePremulCache marks the premultiplication cache as stale. Call this after modifying pixel data directly via Data() or RowBytes().
func (*ImageBuf) IsPremulCached ¶
IsPremulCached returns true if premultiplied data is currently cached.
func (*ImageBuf) PixelBytes ¶
PixelBytes returns a slice of the raw bytes for pixel (x, y). Returns nil if coordinates are out of bounds.
func (*ImageBuf) PixelOffset ¶
PixelOffset returns the byte offset of pixel (x, y) in the data slice. Returns -1 if coordinates are out of bounds.
func (*ImageBuf) PremultipliedData ¶
PremultipliedData returns the image data with premultiplied alpha. For formats already premultiplied or without alpha, returns the original data. The result is cached for efficiency; call InvalidatePremulCache() if the original data has been modified.
func (*ImageBuf) RowBytes ¶
RowBytes returns a slice of the pixel data for row y. Returns nil if y is out of bounds.
func (*ImageBuf) SetPixelBytes ¶
SetPixelBytes sets the raw bytes for pixel (x, y). Returns ErrOutOfBounds if coordinates are outside image bounds. Automatically invalidates the premultiplication cache.
func (*ImageBuf) SetRGBA ¶
SetRGBA sets the color at (x, y) from (r, g, b, a) in 0-255 range. For grayscale formats, uses standard luminance weights. Returns ErrOutOfBounds if coordinates are outside image bounds.
func (*ImageBuf) SubImage ¶
SubImage returns a view into a rectangular region of the image. The returned ImageBuf shares the underlying data with the original. Modifications to the sub-image affect the original and vice versa. Returns nil if the bounds are invalid or outside the image.
func (*ImageBuf) ToStdImage ¶
ToStdImage converts the ImageBuf to a standard library image.Image. Returns *image.RGBA for most formats, *image.Gray for grayscale.
type ImagePattern ¶
type ImagePattern struct {
// contains filtered or unexported fields
}
ImagePattern represents an image-based fill pattern.
ImagePattern applies transformations, spread modes, and interpolation to sample colors from an image. It supports optional mipmap chains for quality downscaling at different scales.
The pattern operates in pattern space where coordinates are transformed via the inverse transform before sampling from the image.
func NewImagePattern ¶
func NewImagePattern(img *ImageBuf) *ImagePattern
NewImagePattern creates a pattern from an image.
Default settings:
- Identity transform
- SpreadPad mode
- InterpBilinear interpolation
- Opacity 1.0 (fully opaque)
- No mipmaps
Returns nil if img is nil.
func (*ImagePattern) Image ¶
func (p *ImagePattern) Image() *ImageBuf
Image returns the underlying image buffer.
func (*ImagePattern) Interpolation ¶
func (p *ImagePattern) Interpolation() InterpolationMode
Interpolation returns the current interpolation mode.
func (*ImagePattern) Mipmaps ¶
func (p *ImagePattern) Mipmaps() *MipmapChain
Mipmaps returns the mipmap chain, or nil if not set.
func (*ImagePattern) Opacity ¶
func (p *ImagePattern) Opacity() float64
Opacity returns the current opacity value.
func (*ImagePattern) Sample ¶
func (p *ImagePattern) Sample(x, y float64) (r, g, b, a byte)
Sample returns the color at the given pattern-space coordinates.
The sampling process:
- Apply inverse transform to convert pattern coords to image coords
- Apply spread mode to handle coordinates outside [0,1]
- Apply interpolation to sample the image
- Apply opacity
Returns (0,0,0,0) if the pattern or image is nil.
func (*ImagePattern) SampleWithScale ¶
func (p *ImagePattern) SampleWithScale(x, y, scale float64) (r, g, b, a byte)
SampleWithScale selects mipmap level based on scale if mipmaps available.
The scale parameter represents the ratio of displayed size to original size:
- scale = 1.0: original size
- scale = 0.5: half size (select mipmap level 1)
- scale = 0.25: quarter size (select mipmap level 2)
Falls back to Sample if no mipmaps are available or scale >= 1.0.
func (*ImagePattern) SpreadMode ¶
func (p *ImagePattern) SpreadMode() SpreadMode
SpreadMode returns the current spread mode.
func (*ImagePattern) Transform ¶
func (p *ImagePattern) Transform() Affine
Transform returns the current transformation matrix.
func (*ImagePattern) WithInterpolation ¶
func (p *ImagePattern) WithInterpolation(mode InterpolationMode) *ImagePattern
WithInterpolation sets the interpolation mode for sampling. Returns the pattern for method chaining.
func (*ImagePattern) WithMipmaps ¶
func (p *ImagePattern) WithMipmaps(chain *MipmapChain) *ImagePattern
WithMipmaps sets the mipmap chain for quality downscaling. Returns the pattern for method chaining.
The mipmap chain is optional. If provided, SampleWithScale will select the appropriate mipmap level based on the scale factor.
func (*ImagePattern) WithOpacity ¶
func (p *ImagePattern) WithOpacity(opacity float64) *ImagePattern
WithOpacity sets the opacity multiplier (0.0 = transparent, 1.0 = opaque). Returns the pattern for method chaining.
Opacity is clamped to [0.0, 1.0].
func (*ImagePattern) WithSpreadMode ¶
func (p *ImagePattern) WithSpreadMode(mode SpreadMode) *ImagePattern
WithSpreadMode sets the spread mode for coordinates outside [0,1]. Returns the pattern for method chaining.
func (*ImagePattern) WithTransform ¶
func (p *ImagePattern) WithTransform(t Affine) *ImagePattern
WithTransform sets the transformation matrix for the pattern. Returns the pattern for method chaining.
The transform converts from pattern space to image space. The inverse is cached for efficient sampling.
type InterpolationMode ¶
type InterpolationMode uint8
InterpolationMode defines how texture sampling is performed.
const ( // InterpNearest selects the closest pixel (no interpolation). // Fast but produces blocky results when scaling. InterpNearest InterpolationMode = iota // InterpBilinear performs linear interpolation between 4 neighboring pixels. // Good balance between quality and performance. InterpBilinear // InterpBicubic performs cubic interpolation using a 4x4 pixel neighborhood. // Highest quality but slower than bilinear. InterpBicubic )
func (InterpolationMode) String ¶
func (m InterpolationMode) String() string
String returns a string representation of the interpolation mode.
type MipmapChain ¶
type MipmapChain struct {
// contains filtered or unexported fields
}
MipmapChain holds pre-computed downscaled versions of an image.
A mipmap chain consists of multiple levels, where each level is half the size of the previous level (both width and height). Level 0 is the original full-resolution image. The chain continues until the smallest dimension reaches 1 pixel.
Mipmaps are used for efficient texture filtering at different scales, reducing aliasing artifacts when rendering scaled images.
func GenerateMipmaps ¶
func GenerateMipmaps(src *ImageBuf) *MipmapChain
GenerateMipmaps creates a mipmap chain from the source image.
Uses a box filter (2x2 average) to downsample each level. The process continues until the smallest dimension reaches 1 pixel. The source image becomes level 0 and is not copied.
Returns nil if src is nil or empty.
func (*MipmapChain) Level ¶
func (m *MipmapChain) Level(n int) *ImageBuf
Level returns the mipmap at the specified level. Level 0 is the original image. Returns nil if level is out of range.
func (*MipmapChain) LevelForScale ¶
func (m *MipmapChain) LevelForScale(scale float64) *ImageBuf
LevelForScale returns the appropriate mipmap level for a given scale factor.
The scale parameter represents the ratio of displayed size to original size:
- scale = 1.0: original size (level 0)
- scale = 0.5: half size (level 1)
- scale = 0.25: quarter size (level 2)
- etc.
The level is calculated as: level = floor(-log2(scale)) The result is clamped to [0, NumLevels-1].
Returns 0 if scale is >= 1.0 or if the chain is nil.
func (*MipmapChain) NumLevels ¶
func (m *MipmapChain) NumLevels() int
NumLevels returns the total number of mipmap levels in the chain. Returns 0 if the chain is nil.
func (*MipmapChain) Release ¶
func (m *MipmapChain) Release()
Release returns all mipmap buffers to the pool except level 0.
Level 0 is the original image and is not returned to the pool since it was provided by the caller. After calling Release, the chain should not be used.
type Pool ¶
type Pool struct {
// contains filtered or unexported fields
}
Pool is a thread-safe pool for reusing ImageBuf instances.
Pool groups buffers by their dimensions and format, allowing efficient reuse of identically-sized buffers. This reduces GC pressure for applications that frequently create and destroy images of similar sizes.
Thread safety: All methods are safe for concurrent use.
func NewPool ¶
NewPool creates a new image buffer pool with the given maximum buffers per bucket. maxPerBucket limits how many buffers of each size/format are retained. A maxPerBucket of 0 means unlimited (use with caution).
type SpreadMode ¶
type SpreadMode uint8
SpreadMode determines how to handle coordinates outside [0,1].
const ( // SpreadPad clamps coordinates to the edge (default). // Values outside [0,1] are clamped to the nearest edge pixel. SpreadPad SpreadMode = iota // SpreadRepeat tiles/repeats the image. // Coordinates wrap around at the boundaries. SpreadRepeat // SpreadReflect mirrors the image at boundaries. // Creates a mirrored tiling effect. SpreadReflect )
func (SpreadMode) String ¶
func (s SpreadMode) String() string
String returns a string representation of the spread mode.