Documentation
¶
Overview ¶
Package imageutil provides image processing utilities built on top of the Go standard library and the official golang.org/x/image subrepository plus the widely-used disintegration/imaging package:
- Decode/Encode: JPEG, PNG, GIF, BMP, TIFF, WebP (WebP decode only)
- Resize: nearest-neighbor, bilinear, CatmullRom (Lanczos-quality), Lanczos — via golang.org/x/image/draw kernels and imaging filters; plus fit-with-padding (letterbox)
- Crop: rectangular, center, smart, aspect-ratio with 9-grid anchor, circular, rounded corners
- Rotate: 90/180/270 degrees
- Flip: horizontal, vertical
- Grayscale: luminance-based conversion
- Adjust: brightness, contrast, gamma, saturation, hue, color temperature, tint
- Filters: box blur, gaussian blur (imaging), sharpen (imaging unsharp mask), edge detect (Sobel), emboss
- Effects: invert, sepia, posterize, threshold (binarize)
- Quality: JPEG re-encode with quality control
- Thumbnail: proportional downscale (with optional padding)
- Watermark: image overlay (center/bottom-right/tiled) and text watermark (center/bottom-right/tiled-rotated, built-in Go font — no .ttf needed)
- Composite: blend modes (multiply/screen/overlay/add/...), border, padding
- Info: dimensions, format detection, histogram & statistics
- Convert: format conversion (e.g. PNG → JPEG)
Quick start ¶
img, _, _ := imageutil.DecodeFile("input.png")
resized := imageutil.ResizeBilinear(img, 200, 0) // width=200, auto height
hq := imageutil.ResizeLanczos(img, 200, 0) // high-quality
cropped := imageutil.Crop(img, image.Rect(10, 10, 110, 110))
blurred := imageutil.GaussianBlur(img, 3, 0)
rounded := imageutil.RoundCorners(img, 24)
imageutil.SaveJPEG(resized, "output.jpg", 85)
Index ¶
- Constants
- Variables
- func AddBorder(img image.Image, thickness int, c color.Color) image.Image
- func AddPadding(img image.Image, targetW, targetH int, bg color.Color) image.Image
- func AdjustBrightness(img image.Image, delta int) image.Image
- func AdjustContrast(img image.Image, factor float64) image.Image
- func AdjustGamma(img image.Image, gamma float64) image.Image
- func AdjustSaturation(img image.Image, factor float64) image.Image
- func AdjustTemperature(img image.Image, delta int) image.Image
- func Blend(base, top image.Image, mode BlendMode) image.Image
- func BoxBlur(img image.Image, radius int) image.Image
- func CompositeWatermark(base image.Image, x, y int, opts CompositeWatermarkOptions) image.Image
- func CompositeWatermarkBottomLeft(base image.Image, opts CompositeWatermarkOptions) image.Image
- func CompositeWatermarkBottomRight(base image.Image, opts CompositeWatermarkOptions) image.Image
- func CompositeWatermarkCenter(base image.Image, opts CompositeWatermarkOptions) image.Image
- func CompositeWatermarkTopLeft(base image.Image, opts CompositeWatermarkOptions) image.Image
- func CompositeWatermarkTopRight(base image.Image, opts CompositeWatermarkOptions) image.Image
- func ConvertFormat(inputPath, outputPath string, quality int) error
- func Crop(img image.Image, rect image.Rectangle) image.Image
- func CropAspectRatio(img image.Image, ratioW, ratioH int, anchor Anchor) image.Image
- func CropAspectRatioResize(img image.Image, ratioW, ratioH, targetW, targetH int, anchor Anchor) image.Image
- func CropCenter(img image.Image, size int) image.Image
- func CropCircle(img image.Image) image.Image
- func CropSmart(img image.Image, targetW, targetH int) image.Image
- func CropTopLeft(img image.Image, size int) image.Image
- func Dimensions(img image.Image) (int, int)
- func EdgeDetect(img image.Image) image.Image
- func Emboss(img image.Image) image.Image
- func Encode(w io.Writer, img image.Image, format Format, quality int) error
- func FlipHorizontal(img image.Image) image.Image
- func FlipVertical(img image.Image) image.Image
- func GaussianBlur(img image.Image, radius int, sigma float64) image.Image
- func Grayscale(img image.Image) image.Image
- func HueRotate(img image.Image, degrees float64) image.Image
- func Invert(img image.Image) image.Image
- func LoadFont(name, path string) error
- func LoadFontBytes(name string, data []byte) error
- func LoadFontTTC(name, path string, index int) error
- func OptimizeForWeb(img image.Image, maxDim int, quality int) ([]byte, error)
- func OptimizeForWebFile(inputPath, outputPath string, maxDim int, quality int) error
- func Posterize(img image.Image, levels int) image.Image
- func ReduceQuality(img image.Image, quality int) ([]byte, error)
- func ReduceQualityFile(inputPath, outputPath string, quality int) error
- func RegisterFont(name string, f *opentype.Font)
- func ResizeBilinear(img image.Image, width, height int) image.Image
- func ResizeCatmullRom(img image.Image, width, height int) image.Image
- func ResizeNearest(img image.Image, width, height int) image.Image
- func ResizeWithPadding(img image.Image, targetW, targetH int, bg color.Color) image.Image
- func Rotate(img image.Image, degrees int) (image.Image, error)
- func Rotate90(img image.Image) image.Image
- func Rotate180(img image.Image) image.Image
- func Rotate270(img image.Image) image.Image
- func RoundCorners(img image.Image, radius int) image.Image
- func Save(img image.Image, path string, format Format, quality int) error
- func SaveByExtension(img image.Image, path string, quality int) error
- func SaveGIF(img image.Image, path string) error
- func SaveJPEG(img image.Image, path string, quality int) error
- func SavePNG(img image.Image, path string) error
- func SaveTIFF(img image.Image, path string) error
- func Sepia(img image.Image) image.Image
- func Sharpen(img image.Image, amount float64) image.Image
- func TextWatermark(base image.Image, text string, x, y int, opts TextWatermarkOptions) image.Image
- func TextWatermarkBottomRight(base image.Image, text string, opts TextWatermarkOptions) image.Image
- func TextWatermarkCenter(base image.Image, text string, opts TextWatermarkOptions) image.Image
- func TextWatermarkTiled(base image.Image, text string, opts TextWatermarkOptions) image.Image
- func Threshold(img image.Image, level int) image.Image
- func Thumbnail(img image.Image, maxWidth, maxHeight int) image.Image
- func ThumbnailWithPadding(img image.Image, targetW, targetH int, bg color.Color) image.Image
- func TileWatermark(base, watermark image.Image, spacingX, spacingY int, opacity float64) image.Image
- func Tint(img image.Image, c color.Color, amount float64) image.Image
- func ToBytes(img image.Image, format Format, quality int) ([]byte, error)
- func Watermark(base, watermark image.Image, x, y int, opacity float64) image.Image
- func WatermarkBottomRight(base, watermark image.Image, opacity float64, padding int) image.Image
- func WatermarkCenter(base, watermark image.Image, opacity float64) image.Image
- type Anchor
- type BlendMode
- type CompositeWatermarkOptions
- type Format
- type Histogram
- type Info
- type Layout
- type TextWatermarkOptions
Constants ¶
const ( FontGoRegular = "goregular" // default FontGoBold = "gobold" FontGoMedium = "gomedium" FontGoItalic = "goitalic" FontGoMono = "gomono" )
Built-in font names that can be used in TextWatermarkOptions.Font without loading any external file.
Variables ¶
var ErrUnsupportedFormat = errors.New("imageutil: unsupported format")
ErrUnsupportedFormat is returned for unsupported image formats.
Functions ¶
func AddBorder ¶
AddBorder adds a solid-color border of the given thickness around the image. The result has dimensions (w+2*thickness) x (h+2*thickness).
func AddPadding ¶
AddPadding pads the image to the target dimensions with a solid background color (letterbox/pillarbox). The source is placed centered. If the source is already larger than the target in either dimension, that axis is left unchanged (no upscaling of the canvas beyond the source for that axis).
func AdjustBrightness ¶
AdjustBrightness adjusts the brightness of an image. delta is in [-255, 255]. Positive values brighten.
func AdjustContrast ¶
AdjustContrast adjusts the contrast of an image. factor of 1.0 means no change. Values > 1 increase contrast.
func AdjustGamma ¶
AdjustGamma applies gamma correction to an image. gamma of 1.0 means no change. Values < 1 brighten, > 1 darken.
func AdjustSaturation ¶
AdjustSaturation adjusts the saturation of an image. factor of 1.0 means no change. 0 produces grayscale.
func AdjustTemperature ¶
AdjustTemperature shifts the color temperature of the image. delta in [-100, 100]: positive warms (more red, less blue), negative cools (more blue, less red). 0 leaves the image unchanged.
func Blend ¶
Blend composites the top image onto the base image using the given mode. The two images need not be the same size: top is anchored at (0,0) and regions outside top are left unchanged. Top's alpha is honored as opacity.
func BoxBlur ¶
BoxBlur applies a box (mean) blur with the given radius. radius=0 returns the original image; radius=1 uses a 3x3 kernel. Uses separable horizontal+vertical passes for O(n) performance.
func CompositeWatermark ¶
CompositeWatermark draws a logo + text watermark at (x, y) from the top-left of the combined layer's bounding box.
func CompositeWatermarkBottomLeft ¶
func CompositeWatermarkBottomLeft(base image.Image, opts CompositeWatermarkOptions) image.Image
CompositeWatermarkBottomLeft draws a logo + text watermark at the bottom-left corner with the given padding.
func CompositeWatermarkBottomRight ¶
func CompositeWatermarkBottomRight(base image.Image, opts CompositeWatermarkOptions) image.Image
CompositeWatermarkBottomRight draws a logo + text watermark at the bottom-right corner with the given padding.
func CompositeWatermarkCenter ¶
func CompositeWatermarkCenter(base image.Image, opts CompositeWatermarkOptions) image.Image
CompositeWatermarkCenter draws a logo + text watermark centered on the base image.
func CompositeWatermarkTopLeft ¶
func CompositeWatermarkTopLeft(base image.Image, opts CompositeWatermarkOptions) image.Image
CompositeWatermarkTopLeft draws a logo + text watermark at the top-left corner with the given padding.
func CompositeWatermarkTopRight ¶
func CompositeWatermarkTopRight(base image.Image, opts CompositeWatermarkOptions) image.Image
CompositeWatermarkTopRight draws a logo + text watermark at the top-right corner with the given padding.
func ConvertFormat ¶
ConvertFormat reads an image file and saves it in a different format.
func Crop ¶
Crop extracts a rectangular region from an image. The rectangle is clamped to the image bounds.
func CropAspectRatio ¶
CropAspectRatio crops the source to the given aspect ratio (ratioW:ratioH) using the specified anchor. The result keeps the source resolution (no resize). If the source already matches the ratio, it is returned unchanged.
func CropAspectRatioResize ¶
func CropAspectRatioResize(img image.Image, ratioW, ratioH, targetW, targetH int, anchor Anchor) image.Image
CropAspectRatioResize crops to the given aspect ratio using the anchor, then resizes the result to exactly targetW x targetH (bilinear).
func CropCenter ¶
CropCenter crops a square region from the center of the image.
func CropCircle ¶
CropCircle crops the image to a circle inscribed in the smaller dimension, centered. Pixels outside the circle are fully transparent. The result is RGBA and has the same dimensions as the source.
func CropSmart ¶
CropSmart crops and resizes to the target dimensions, filling the frame (like CSS object-fit: cover). The source is cropped to match the target aspect ratio, then resized.
func CropTopLeft ¶
CropTopLeft crops a square region from the top-left corner.
func Dimensions ¶
Dimensions returns the width and height of an image.
func EdgeDetect ¶
EdgeDetect applies a Sobel edge-detection filter and returns a grayscale-ish image where edges are bright on a black background.
func Encode ¶
Encode encodes an image to the specified format and writes to w. WebP is not supported for encoding (golang.org/x/image/webp is decode-only); use a dedicated WebP encoder if needed.
func FlipHorizontal ¶
FlipHorizontal flips the image horizontally (left-right).
func FlipVertical ¶
FlipVertical flips the image vertically (top-bottom).
func GaussianBlur ¶
GaussianBlur applies a gaussian blur with the given sigma (standard deviation, in pixels). sigma <= 0 returns the original image.
The radius parameter is kept for backward compatibility but ignored — imaging.Blur derives the kernel radius from sigma automatically. A reasonable mapping is sigma ≈ radius/2.
func HueRotate ¶
HueRotate rotates the hue of every pixel by the given degrees (0-360). 0/360 leaves colors unchanged; 180 inverts hues.
func LoadFont ¶
LoadFont reads a TrueType / OpenType file (.ttf / .otf) from path, parses it, and registers it under name. The name can then be used in TextWatermarkOptions.Font. Returns an error if the file cannot be read or parsed.
func LoadFontBytes ¶
LoadFontBytes registers a font from raw TTF/OTF bytes under name. Useful when the font is embedded via go:embed or obtained from another source.
func LoadFontTTC ¶
LoadFontTTC reads a TrueType Collection (.ttc) file, extracts the font at the given index, and registers it under name. This is needed for CJK fonts on macOS (PingFang.ttc, Hiragino Sans GB.ttc, etc.) which ship as .ttc collections rather than standalone .ttf files. Returns an error if the file cannot be read, the index is out of range, or the extracted font cannot be parsed.
func OptimizeForWeb ¶
OptimizeForWeb resizes and compresses an image for web use. It resizes to fit within maxDim x maxDim (preserving aspect ratio), then encodes as JPEG at the given quality.
func OptimizeForWebFile ¶
OptimizeForWebFile reads, optimizes, and saves an image for web use.
func Posterize ¶
Posterize reduces the number of distinct colors per channel. levels in [2, 255]: 2 yields a 2-tone posterization per channel, 255 leaves the image effectively unchanged.
func ReduceQuality ¶
ReduceQuality re-encodes a JPEG image at a lower quality to reduce file size.
func ReduceQualityFile ¶
ReduceQualityFile reads a JPEG file, re-encodes at lower quality, and saves.
func RegisterFont ¶
RegisterFont registers a parsed OpenType font under the given name. The name can then be used in TextWatermarkOptions.Font. Registering an existing name overwrites it.
func ResizeBilinear ¶
ResizeBilinear resizes an image using bilinear interpolation via golang.org/x/image/draw. If width or height is 0, it is computed to preserve aspect ratio. If both are 0, the original image is returned.
func ResizeCatmullRom ¶
ResizeCatmullRom resizes an image using the CatmullRom cubic kernel via golang.org/x/image/draw. This is a high-quality interpolation suitable for downscaling photos. If width or height is 0, it is computed to preserve aspect ratio. If both are 0, the original image is returned.
func ResizeNearest ¶
ResizeNearest resizes an image using nearest-neighbor interpolation via golang.org/x/image/draw. If width or height is 0, it is computed to preserve aspect ratio. If both are 0, the original image is returned.
func ResizeWithPadding ¶
ResizeWithPadding resizes the image to fit within targetW x targetH while preserving aspect ratio, then centers it on a solid background canvas of exactly targetW x targetH (letterbox / "object-fit: contain").
If the source is smaller than the target in both dimensions, it is still upscaled to fit (no upscaling-skip). For a no-upscale variant, see ThumbnailWithPadding.
bg is the padding color (e.g. color.Black or color.White).
func RoundCorners ¶
RoundCorners rounds the corners of the image with the given radius. Areas outside the rounded rectangle are transparent. The result is RGBA with the same dimensions as the source.
func Save ¶
Save saves an image in the specified format. WebP is not supported for encoding (decode-only); use a dedicated WebP encoder if needed.
func SaveByExtension ¶
SaveByExtension saves an image, inferring the format from the file extension.
func Sharpen ¶
Sharpen applies an unsharp-mask sharpening filter via disintegration/imaging. amount is the sigma of the gaussian used for the unsharp mask; typical values are 0.5–2.0. amount <= 0 returns the original image.
func TextWatermark ¶
TextWatermark draws a text watermark at (x, y) from the top-left of the text bounding box.
func TextWatermarkBottomRight ¶
TextWatermarkBottomRight draws a text watermark at the bottom-right corner with the given padding.
func TextWatermarkCenter ¶
TextWatermarkCenter draws a text watermark centered on the base image.
func TextWatermarkTiled ¶
TextWatermarkTiled repeats the text across the entire image, rotated by opts.Angle (degrees, clockwise). Typical use: a -30° "CONFIDENTIAL" or "DEMO" overlay. opts.Padding controls spacing between tiles (default 50).
func Threshold ¶
Threshold binarizes the image: pixels whose luminance is >= level become white, others become black. level in [0, 255].
func Thumbnail ¶
Thumbnail creates a thumbnail that fits within the given dimensions, preserving aspect ratio. The result is never larger than the original.
func ThumbnailWithPadding ¶
ThumbnailWithPadding is like ResizeWithPadding but never upscales: if the source already fits within targetW x targetH, it is centered as-is on the padding canvas.
func TileWatermark ¶
func TileWatermark(base, watermark image.Image, spacingX, spacingY int, opacity float64) image.Image
TileWatermark repeats the watermark across the entire base image with the given spacing between tiles. Useful for diagonal "demo" / "confidential" overlays. opacity in [0, 1].
func Tint ¶
Tint applies a color tint over the image. amount in [0, 1] controls the strength: 0 leaves the image unchanged, 1 fully replaces color with c.
func Watermark ¶
Watermark overlays a watermark image onto a base image at the given position. opacity is in [0, 1]. The watermark is drawn at (x, y) from the top-left.
func WatermarkBottomRight ¶
WatermarkBottomRight overlays a watermark at the bottom-right corner.
Types ¶
type Anchor ¶
type Anchor int
Anchor selects which of 9 regions of the source to keep when cropping to a target aspect ratio. Layout:
TopLeft TopCenter TopRight MiddleLeft MiddleCenter MiddleRight BottomLeft BottomCenter BottomRight
type BlendMode ¶
type BlendMode int
BlendMode is a per-channel compositing operation used by Blend.
const ( // BlendNormal places the top layer over the base, honoring top's alpha. BlendNormal BlendMode = iota // BlendMultiply: result = base * top / 255. Darkens. BlendMultiply // BlendScreen: result = 255 - (255-base)*(255-top)/255. Lightens. BlendScreen // BlendOverlay: multiply where base < 128, screen otherwise. Increases contrast. BlendOverlay // BlendAdd (Linear Dodge): result = base + top. Clips to 255. BlendAdd // BlendSubtract: result = base - top. Clips to 0. BlendSubtract // BlendDifference: result = |base - top|. BlendDifference // BlendDarken: result = min(base, top). BlendDarken // BlendLighten: result = max(base, top). BlendLighten )
type CompositeWatermarkOptions ¶
type CompositeWatermarkOptions struct {
// Logo is the image (e.g. a brand mark) to place alongside the text.
// Required — if nil, falls back to a pure text watermark.
Logo image.Image
// Text is the label drawn next to the logo. May be empty for a pure
// image watermark.
Text string
// Font selects a registered font by name. Empty / "goregular" uses the
// default built-in Go regular font.
Font string
// FontSize is the font size in points. Default 24.
FontSize float64
// TextColor is the text color. Default color.White.
TextColor color.Color
// Opacity in [0, 1] for the whole composite layer. Default 0.85.
Opacity float64
// Layout controls how logo and text are arranged. Default LogoLeftTextRight.
Layout Layout
// Spacing is the gap (in pixels) between the logo and the text. Default 8.
Spacing int
// Padding is the margin from the edge for positional variants. Default 16.
Padding int
// LogoHeight scales the logo so its height matches this many pixels.
// If 0, the logo is used at its natural size. Useful for aligning the
// logo with the text cap height.
LogoHeight int
}
CompositeWatermarkOptions controls rendering of a combined logo + text watermark.
type Format ¶
type Format string
Format represents an image file format.
func DecodeConfig ¶
DecodeConfig decodes image config (dimensions, format) without full decode.
func DecodeFile ¶
DecodeFile decodes an image from a file path.
func FormatFromExtension ¶
FormatFromExtension returns the format for a file extension.
type Histogram ¶
type Histogram struct {
Width int
Height int
Total int // total pixel count
R, G, B, A [256]uint32 // per-channel counts
Lum [256]uint32 // luminance histogram (per-pixel weighted sum)
// Statistics (over luminance).
Mean float64
StdDev float64
Min uint8
Max uint8
}
Histogram holds per-channel 256-bin intensity distributions and basic statistics. Counts are pixel counts; Prob[i] = Count[i] / TotalPixels.
func CalcHistogram ¶
CalcHistogram computes the histogram and luminance statistics of an image. Luminance uses the standard ITU-R BT.601 weights (0.299, 0.587, 0.114).
func (*Histogram) Contrast ¶
Contrast returns a simple contrast metric: the standard deviation of luminance (same as StdDev).
type Layout ¶
type Layout int
Layout describes how the logo and text are arranged within a composite watermark.
const ( // LayoutLogoLeftTextRight places the logo to the left of the text: // [LOGO] Text LayoutLogoLeftTextRight Layout = iota // LayoutLogoRightTextLeft places the logo to the right of the text: // Text [LOGO] LayoutLogoRightTextLeft // LayoutLogoTopTextBottom stacks the logo above the text: // [LOGO] // Text LayoutLogoTopTextBottom // LayoutLogoBottomTextTop stacks the text above the logo: // Text // [LOGO] LayoutLogoBottomTextTop )
type TextWatermarkOptions ¶
type TextWatermarkOptions struct {
// Font selects a registered font by name. Empty / "goregular" uses the
// default built-in Go regular font. Use one of the FontGo* constants for
// the other built-in styles, or a name you registered via RegisterFont /
// LoadFont.
Font string
// FontSize is the font size in points. Default 24.
FontSize float64
// Color is the text color. Default color.White.
Color color.Color
// Opacity in [0, 1]. Default 0.5.
Opacity float64
// Angle is the rotation in degrees (clockwise). 0 = horizontal.
// Used by TextWatermarkTiled and ignored by the positional variants.
Angle float64
// Padding is the margin from the edge (in pixels) for positional variants,
// or the spacing between tiles for Tiled. Default 10 / 50.
Padding int
}
TextWatermarkOptions controls text watermark rendering.