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 (encode via github.com/deepteams/webp — pure Go, no CGo)
- 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
- Cinematic looks: vintage, cool, warm (per-pixel, strength-controlled)
- Effects: invert, sepia, posterize, threshold (binarize), vignette, noise/grain, pixelate (mosaic)
- 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), PNG → ICO (favicon)
- Animated GIF: per-frame resize/optimize preserving animation
- Color: hex color parsing (#rgb / #rgba / #rrggbb / #rrggbbaa)
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)
imageutil.SaveWebP(resized, "output.webp", 80) // WebP encode
imageutil.SaveICO(img, "favicon.ico", nil) // multi-size ICO
Index ¶
- Constants
- Variables
- func AddBorder(img image.Image, thickness int, c color.Color) image.Image
- func AddNoise(img image.Image, amount int, monochrome bool, rng *rand.Rand) 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 Cool(img image.Image, strength float64) image.Image
- 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 DecodeAnimatedGIF(r io.Reader) (*gif.GIF, error)
- 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 EncodeAnimatedGIF(w io.Writer, g *gif.GIF) error
- func FlipHorizontal(img image.Image) image.Image
- func FlipVertical(img image.Image) image.Image
- func FormatHexColor(c color.Color) string
- 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 MapAnimatedGIFFrames(g *gif.GIF, fn func(frame image.Image) image.Image) *gif.GIF
- func MustParseHexColor(s string) color.RGBA
- func OptimizeAnimatedGIF(g *gif.GIF, maxDim int) ([]byte, error)
- func OptimizeAnimatedGIFFile(inputPath, outputPath string, maxDim int) error
- func OptimizeForWeb(img image.Image, maxDim int, quality int) ([]byte, error)
- func OptimizeForWebFile(inputPath, outputPath string, maxDim int, quality int) error
- func ParseHexColor(s string) (color.RGBA, error)
- func Pixelate(img image.Image, blockSize int) image.Image
- 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 ResizeAnimatedGIF(g *gif.GIF, width, height int) *gif.GIF
- func ResizeAnimatedGIFFile(inputPath, outputPath string, width, height int) error
- 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 SaveICO(img image.Image, path string, sizes []int) 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 SaveWebP(img image.Image, path string, quality int) 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 ToICO(img image.Image, sizes []int) ([]byte, error)
- func Vignette(img image.Image, strength, size float64) image.Image
- func Vintage(img image.Image, strength float64) image.Image
- func Warm(img image.Image, strength float64) image.Image
- 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 DefaultICOSizes = []int{256, 128, 64, 48, 32, 16}
DefaultICOSizes is the set of sizes embedded by SaveICO/ToICO when no sizes are explicitly provided. Matches the sizes used by Windows favicon conventions: 256, 128, 64, 48, 32, 16.
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 AddNoise ¶ added in v0.2.0
AddNoise adds random noise to each pixel, simulating film grain. amount in [0, 255] is the maximum per-channel perturbation. monochrome=true applies the same delta to R, G, B (grayscale noise); false applies independent deltas per channel (color noise). A nil rng uses a default math/rand source.
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 Cool ¶ added in v0.2.0
Cool applies a cool-toned look: shifted toward blue/cyan, slightly desaturated, with a subtle contrast boost. strength in [0, 1].
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 DecodeAnimatedGIF ¶ added in v0.2.0
DecodeAnimatedGIF reads an animated GIF from r and returns the full multi-frame structure. Non-animated GIFs are returned as a single-frame GIF (len(g.Image) == 1).
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 encoding is supported via github.com/deepteams/webp (pure Go, no CGo). For WebP, quality is in [1, 100] (lossy); pass a negative quality to use lossless encoding.
func EncodeAnimatedGIF ¶ added in v0.2.0
EncodeAnimatedGIF writes an animated GIF to w.
func FlipHorizontal ¶
FlipHorizontal flips the image horizontally (left-right).
func FlipVertical ¶
FlipVertical flips the image vertically (top-bottom).
func FormatHexColor ¶ added in v0.2.0
FormatHexColor converts a color.Color to a "#rrggbb" hex string (alpha omitted when fully opaque) or "#rrggbbaa" when alpha < 255.
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 MapAnimatedGIFFrames ¶ added in v0.2.0
MapAnimatedGIFFrames applies fn to every frame of g and returns a new *gif.GIF with the transformed frames. The disposal method, delays and other animation metadata are preserved. fn receives the frame as an image.Image and must return a new *image.Paletted (or any image.Image that can be paletted — non-paletted returns are quantized to 256 colors via a uniform palette).
This is the building block for ResizeAnimatedGIF, OptimizeAnimatedGIF and any custom per-frame effect.
func MustParseHexColor ¶ added in v0.2.0
MustParseHexColor is like ParseHexColor but panics on error. Useful for package-level color constants.
func OptimizeAnimatedGIF ¶ added in v0.2.0
OptimizeAnimatedGIF resizes each frame to fit within maxDim×maxDim (no upscaling) and returns the encoded bytes. Convenience wrapper for the common "shrink this GIF for the web" use case.
func OptimizeAnimatedGIFFile ¶ added in v0.2.0
OptimizeAnimatedGIFFile reads an animated GIF, shrinks each frame to fit within maxDim×maxDim, and writes the result to outputPath.
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 ParseHexColor ¶ added in v0.2.0
ParseHexColor parses a hex color string into a color.RGBA. Supported formats (with or without leading '#'):
- "#rgb" → e.g. "#f80" = #ff8800, alpha=255
- "#rgba" → e.g. "#f80a" = #ff8800aa
- "#rrggbb" → e.g. "#ff8800", alpha=255
- "#rrggbbaa" → e.g. "#ff8800aa"
Uppercase and lowercase hex digits are accepted. The leading '#' is optional.
func Pixelate ¶ added in v0.2.0
Pixelate block-averages the image into blocks of the given size, producing a mosaic/pixelation effect. blockSize is the side length of each block in pixels; values <= 1 return the original image.
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 ResizeAnimatedGIF ¶ added in v0.2.0
ResizeAnimatedGIF resizes every frame of an animated GIF to width×height (preserving aspect ratio when one dimension is 0) and returns a new *gif.GIF. Uses bilinear interpolation for a good speed/quality balance.
func ResizeAnimatedGIFFile ¶ added in v0.2.0
ResizeAnimatedGIFFile reads an animated GIF from inputPath, resizes every frame, and writes the result to outputPath.
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 encoding is supported via github.com/deepteams/webp. For WebP, pass a negative quality for lossless encoding.
func SaveByExtension ¶
SaveByExtension saves an image, inferring the format from the file extension.
func SaveICO ¶ added in v0.2.0
SaveICO encodes img into a multi-size Windows ICO file and writes it to path. See ToICO for details on sizes and behavior.
func SaveWebP ¶ added in v0.2.0
SaveWebP saves an image as WebP with the given quality (1-100, lossy). Pass a negative quality to use lossless encoding.
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 ToICO ¶ added in v0.2.0
ToICO encodes img into a multi-size Windows ICO file and returns the bytes. Each size in sizes is produced by downscaling img with a high-quality bilinear filter and then PNG-encoding the result (Vista+ supports PNG inside ICO). If sizes is nil/empty, DefaultICOSizes is used.
The source image should ideally be square; non-square sources are center-cropped to a square before downscaling so the resulting icon is not distorted.
func Vignette ¶ added in v0.2.0
Vignette darkens the corners of the image with a radial gradient. strength in [0, 1] controls how dark the corners get (0 = no effect, 1 = fully black at the farthest corner). size in [0, 1] controls the falloff: 0 = sharp transition at the very edge, 1 = vignette starts from the center. A typical value is 0.5.
func Vintage ¶ added in v0.2.0
Vintage applies a faded, warm-toned vintage look: lifted blacks, reduced contrast, shifted toward amber/sepia, with a subtle vignette. strength in [0, 1] controls how strong the effect is (0 = no change).
func Warm ¶ added in v0.2.0
Warm applies a warm-toned look: shifted toward orange/yellow, slightly saturated, with a gentle contrast reduction for a soft golden-hour feel. strength in [0, 1].
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.