imageutil

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2026 License: MIT Imports: 28 Imported by: 0

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

View Source
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

View Source
var ErrUnsupportedFormat = errors.New("imageutil: unsupported format")

ErrUnsupportedFormat is returned for unsupported image formats.

Functions

func AddBorder

func AddBorder(img image.Image, thickness int, c color.Color) image.Image

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

func AddPadding(img image.Image, targetW, targetH int, bg color.Color) image.Image

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

func AdjustBrightness(img image.Image, delta int) image.Image

AdjustBrightness adjusts the brightness of an image. delta is in [-255, 255]. Positive values brighten.

func AdjustContrast

func AdjustContrast(img image.Image, factor float64) image.Image

AdjustContrast adjusts the contrast of an image. factor of 1.0 means no change. Values > 1 increase contrast.

func AdjustGamma

func AdjustGamma(img image.Image, gamma float64) image.Image

AdjustGamma applies gamma correction to an image. gamma of 1.0 means no change. Values < 1 brighten, > 1 darken.

func AdjustSaturation

func AdjustSaturation(img image.Image, factor float64) image.Image

AdjustSaturation adjusts the saturation of an image. factor of 1.0 means no change. 0 produces grayscale.

func AdjustTemperature

func AdjustTemperature(img image.Image, delta int) image.Image

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

func Blend(base, top image.Image, mode BlendMode) image.Image

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

func BoxBlur(img image.Image, radius int) image.Image

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

func CompositeWatermark(base image.Image, x, y int, opts CompositeWatermarkOptions) image.Image

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

func ConvertFormat(inputPath, outputPath string, quality int) error

ConvertFormat reads an image file and saves it in a different format.

func Crop

func Crop(img image.Image, rect image.Rectangle) image.Image

Crop extracts a rectangular region from an image. The rectangle is clamped to the image bounds.

func CropAspectRatio

func CropAspectRatio(img image.Image, ratioW, ratioH int, anchor Anchor) image.Image

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

func CropCenter(img image.Image, size int) image.Image

CropCenter crops a square region from the center of the image.

func CropCircle

func CropCircle(img image.Image) image.Image

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

func CropSmart(img image.Image, targetW, targetH int) image.Image

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

func CropTopLeft(img image.Image, size int) image.Image

CropTopLeft crops a square region from the top-left corner.

func Dimensions

func Dimensions(img image.Image) (int, int)

Dimensions returns the width and height of an image.

func EdgeDetect

func EdgeDetect(img image.Image) image.Image

EdgeDetect applies a Sobel edge-detection filter and returns a grayscale-ish image where edges are bright on a black background.

func Emboss

func Emboss(img image.Image) image.Image

Emboss applies an emboss effect, giving the image a 3D relief appearance.

func Encode

func Encode(w io.Writer, img image.Image, format Format, quality int) error

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

func FlipHorizontal(img image.Image) image.Image

FlipHorizontal flips the image horizontally (left-right).

func FlipVertical

func FlipVertical(img image.Image) image.Image

FlipVertical flips the image vertically (top-bottom).

func GaussianBlur

func GaussianBlur(img image.Image, radius int, sigma float64) image.Image

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 Grayscale

func Grayscale(img image.Image) image.Image

Grayscale converts an image to grayscale using luminance weights.

func HueRotate

func HueRotate(img image.Image, degrees float64) image.Image

HueRotate rotates the hue of every pixel by the given degrees (0-360). 0/360 leaves colors unchanged; 180 inverts hues.

func Invert

func Invert(img image.Image) image.Image

Invert inverts the colors of an image (negative effect).

func LoadFont

func LoadFont(name, path string) error

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

func LoadFontBytes(name string, data []byte) error

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

func LoadFontTTC(name, path string, index int) error

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

func OptimizeForWeb(img image.Image, maxDim int, quality int) ([]byte, error)

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

func OptimizeForWebFile(inputPath, outputPath string, maxDim int, quality int) error

OptimizeForWebFile reads, optimizes, and saves an image for web use.

func Posterize

func Posterize(img image.Image, levels int) image.Image

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

func ReduceQuality(img image.Image, quality int) ([]byte, error)

ReduceQuality re-encodes a JPEG image at a lower quality to reduce file size.

func ReduceQualityFile

func ReduceQualityFile(inputPath, outputPath string, quality int) error

ReduceQualityFile reads a JPEG file, re-encodes at lower quality, and saves.

func RegisterFont

func RegisterFont(name string, f *opentype.Font)

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

func ResizeBilinear(img image.Image, width, height int) image.Image

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

func ResizeCatmullRom(img image.Image, width, height int) image.Image

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

func ResizeNearest(img image.Image, width, height int) image.Image

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

func ResizeWithPadding(img image.Image, targetW, targetH int, bg color.Color) image.Image

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 Rotate

func Rotate(img image.Image, degrees int) (image.Image, error)

Rotate rotates by the given degrees. Only 90, 180, 270 are supported.

func Rotate90

func Rotate90(img image.Image) image.Image

Rotate90 rotates the image 90 degrees clockwise.

func Rotate180

func Rotate180(img image.Image) image.Image

Rotate180 rotates the image 180 degrees.

func Rotate270

func Rotate270(img image.Image) image.Image

Rotate270 rotates the image 270 degrees clockwise (90 counter-clockwise).

func RoundCorners

func RoundCorners(img image.Image, radius int) image.Image

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

func Save(img image.Image, path string, format Format, quality int) error

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

func SaveByExtension(img image.Image, path string, quality int) error

SaveByExtension saves an image, inferring the format from the file extension.

func SaveGIF

func SaveGIF(img image.Image, path string) error

SaveGIF saves an image as GIF.

func SaveJPEG

func SaveJPEG(img image.Image, path string, quality int) error

SaveJPEG saves an image as JPEG with the given quality (1-100).

func SavePNG

func SavePNG(img image.Image, path string) error

SavePNG saves an image as PNG.

func SaveTIFF

func SaveTIFF(img image.Image, path string) error

SaveTIFF saves an image as TIFF (Deflate-compressed).

func Sepia

func Sepia(img image.Image) image.Image

Sepia applies a sepia tone effect.

func Sharpen

func Sharpen(img image.Image, amount float64) image.Image

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

func TextWatermark(base image.Image, text string, x, y int, opts TextWatermarkOptions) image.Image

TextWatermark draws a text watermark at (x, y) from the top-left of the text bounding box.

func TextWatermarkBottomRight

func TextWatermarkBottomRight(base image.Image, text string, opts TextWatermarkOptions) image.Image

TextWatermarkBottomRight draws a text watermark at the bottom-right corner with the given padding.

func TextWatermarkCenter

func TextWatermarkCenter(base image.Image, text string, opts TextWatermarkOptions) image.Image

TextWatermarkCenter draws a text watermark centered on the base image.

func TextWatermarkTiled

func TextWatermarkTiled(base image.Image, text string, opts TextWatermarkOptions) image.Image

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

func Threshold(img image.Image, level int) image.Image

Threshold binarizes the image: pixels whose luminance is >= level become white, others become black. level in [0, 255].

func Thumbnail

func Thumbnail(img image.Image, maxWidth, maxHeight int) image.Image

Thumbnail creates a thumbnail that fits within the given dimensions, preserving aspect ratio. The result is never larger than the original.

func ThumbnailWithPadding

func ThumbnailWithPadding(img image.Image, targetW, targetH int, bg color.Color) image.Image

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

func Tint(img image.Image, c color.Color, amount float64) image.Image

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 ToBytes

func ToBytes(img image.Image, format Format, quality int) ([]byte, error)

ToBytes encodes an image to a byte slice.

func Watermark

func Watermark(base, watermark image.Image, x, y int, opacity float64) image.Image

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

func WatermarkBottomRight(base, watermark image.Image, opacity float64, padding int) image.Image

WatermarkBottomRight overlays a watermark at the bottom-right corner.

func WatermarkCenter

func WatermarkCenter(base, watermark image.Image, opacity float64) image.Image

WatermarkCenter overlays a watermark at the center of the base image.

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
const (
	AnchorTopLeft Anchor = iota
	AnchorTopCenter
	AnchorTopRight
	AnchorMiddleLeft
	AnchorMiddleCenter
	AnchorBottomLeft
	AnchorBottomCenter
	AnchorBottomRight
)

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 {
	// 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.

const (
	FormatJPEG Format = "jpeg"
	FormatPNG  Format = "png"
	FormatGIF  Format = "gif"
	FormatBMP  Format = "bmp"
	FormatTIFF Format = "tiff"
	FormatWebP Format = "webp"
)

func Decode

func Decode(r io.Reader) (image.Image, Format, error)

Decode decodes an image from a reader and returns the image and its format.

func DecodeConfig

func DecodeConfig(r io.Reader) (image.Config, Format, error)

DecodeConfig decodes image config (dimensions, format) without full decode.

func DecodeFile

func DecodeFile(path string) (image.Image, Format, error)

DecodeFile decodes an image from a file path.

func FormatFromExtension

func FormatFromExtension(ext string) (Format, error)

FormatFromExtension returns the format for a file extension.

func FromBytes

func FromBytes(data []byte) (image.Image, Format, error)

FromBytes decodes an image from a byte slice.

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

func CalcHistogram(img image.Image) *Histogram

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

func (h *Histogram) Contrast() float64

Contrast returns a simple contrast metric: the standard deviation of luminance (same as StdDev).

func (*Histogram) Luminance

func (h *Histogram) Luminance() [256]uint32

Luminance returns the luminance histogram (256 bins) computed per-pixel during construction. The sum of all bins equals Total.

func (*Histogram) MeanRGB

func (h *Histogram) MeanRGB() (float64, float64, float64)

MeanRGB returns the average R, G, B values (0-255 each).

type Info

type Info struct {
	Width  int
	Height int
	Format Format
}

Info holds basic image information.

func GetInfo

func GetInfo(path string) (*Info, error)

GetInfo returns image info from a file.

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.

Jump to

Keyboard shortcuts

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