Documentation
¶
Overview ¶
Package imgx provides basic image processing functions (resize, rotate, crop, brightness/contrast adjustments, etc.).
All the image processing functions provided by the package accept any image type that implements image.Image interface as an input, and return a new image of *image.NRGBA type (32bit RGBA colors, non-premultiplied alpha).
Installation ¶
To install the CLI tool:
go install github.com/razzkumar/imgx/cmd/imgx@latest
Example ¶
package main
import (
"image"
"image/color"
"log"
"github.com/razzkumar/imgx"
)
func main() {
// Load a test image.
src, err := imgx.Load("testdata/flower.jpg")
if err != nil {
log.Fatalf("failed to load image: %v", err)
}
// Crop the original image to 300x300px size using the center anchor.
src = src.CropAnchor(300, 300, imgx.Center)
// Resize the cropped image to width = 200px preserving the aspect ratio.
src = src.Resize(200, 0, imgx.Lanczos)
// Create a blurred version of the image.
img1 := src.Blur(5)
// Create a grayscale version of the image with higher contrast and sharpness.
img2 := src.Grayscale().AdjustContrast(20).Sharpen(2)
// Create an inverted version of the image.
img3 := src.Invert()
// Create an embossed version of the image using a convolution filter.
img4 := src.Convolve3x3(
[9]float64{
-1, -1, 0,
-1, 1, 1,
0, 1, 1,
},
nil,
)
// Create a new image and paste the four produced images into it.
dst := imgx.NewImage(400, 400, color.NRGBA{0, 0, 0, 0})
dst = dst.Paste(img1, image.Pt(0, 0))
dst = dst.Paste(img2, image.Pt(0, 200))
dst = dst.Paste(img3, image.Pt(200, 0))
dst = dst.Paste(img4, image.Pt(200, 200))
// Save the resulting image as JPEG.
err = dst.Save("testdata/out_example.jpg")
if err != nil {
log.Fatalf("failed to save image: %v", err)
}
}
Index ¶
- Constants
- Variables
- func AdjustBrightness(img image.Image, percentage float64) *image.NRGBA
- func AdjustContrast(img image.Image, percentage float64) *image.NRGBA
- func AdjustFunc(img image.Image, fn func(c color.NRGBA) color.NRGBA) *image.NRGBA
- func AdjustGamma(img image.Image, gamma float64) *image.NRGBA
- func AdjustHue(img image.Image, shift float64) *image.NRGBA
- func AdjustSaturation(img image.Image, percentage float64) *image.NRGBA
- func AdjustSigmoid(img image.Image, midpoint, factor float64) *image.NRGBA
- func Blur(img image.Image, sigma float64) *image.NRGBA
- func Clone(img image.Image) *image.NRGBA
- func Convolve3x3(img image.Image, kernel [9]float64, options *ConvolveOptions) *image.NRGBA
- func Convolve5x5(img image.Image, kernel [25]float64, options *ConvolveOptions) *image.NRGBA
- func Crop(img image.Image, rect image.Rectangle) *image.NRGBA
- func CropAnchor(img image.Image, width, height int, anchor Anchor) *image.NRGBA
- func CropCenter(img image.Image, width, height int) *image.NRGBA
- func Decode(r io.Reader, opts ...DecodeOption) (image.Image, error)
- func Encode(w io.Writer, img image.Image, format Format, opts ...EncodeOption) error
- func Fill(img image.Image, width, height int, anchor Anchor, filter ResampleFilter) *image.NRGBA
- func Fit(img image.Image, width, height int, filter ResampleFilter) *image.NRGBA
- func FlipH(img image.Image) *image.NRGBA
- func FlipV(img image.Image) *image.NRGBA
- func GetAddMetadata() bool
- func GetDefaultAuthor() string
- func Grayscale(img image.Image) *image.NRGBA
- func Histogram(img image.Image) [256]float64
- func Invert(img image.Image) *image.NRGBA
- func New(width, height int, fillColor color.Color) *image.NRGBA
- func Overlay(background, img image.Image, pos image.Point, opacity float64) *image.NRGBA
- func OverlayCenter(background, img image.Image, opacity float64) *image.NRGBA
- func Paste(background, img image.Image, pos image.Point) *image.NRGBA
- func PasteCenter(background, img image.Image) *image.NRGBA
- func Resize(img image.Image, width, height int, filter ResampleFilter) *image.NRGBA
- func Rotate(img image.Image, angle float64, bgColor color.Color) *image.NRGBA
- func Rotate180(img image.Image) *image.NRGBA
- func Rotate270(img image.Image) *image.NRGBA
- func Rotate90(img image.Image) *image.NRGBA
- func SetAddMetadata(enabled bool)
- func SetDefaultAuthor(author string)
- func SetMaxProcs(value int)
- func Sharpen(img image.Image, sigma float64) *image.NRGBA
- func Thumbnail(img image.Image, width, height int, filter ResampleFilter) *image.NRGBA
- func Transpose(img image.Image) *image.NRGBA
- func Transverse(img image.Image) *image.NRGBA
- func Watermark(img image.Image, opts WatermarkOptions) *image.NRGBA
- type Anchor
- type Config
- type ConvolveOptions
- type DecodeOption
- type EncodeOption
- type Format
- type Image
- func (img *Image) AdjustBrightness(percentage float64) *Image
- func (img *Image) AdjustContrast(percentage float64) *Image
- func (img *Image) AdjustGamma(gamma float64) *Image
- func (img *Image) AdjustHue(shift float64) *Image
- func (img *Image) AdjustSaturation(percentage float64) *Image
- func (img *Image) AdjustSigmoid(midpoint, factor float64) *Image
- func (img *Image) Blur(sigma float64) *Image
- func (img *Image) Bounds() image.Rectangle
- func (img *Image) Convolve3x3(kernel [9]float64, options *ConvolveOptions) *Image
- func (img *Image) Convolve5x5(kernel [25]float64, options *ConvolveOptions) *Image
- func (img *Image) Crop(rect image.Rectangle) *Image
- func (img *Image) CropAnchor(width, height int, anchor Anchor) *Image
- func (img *Image) CropCenter(width, height int) *Image
- func (img *Image) Detect(ctx context.Context, provider string, opts ...*detection.DetectOptions) (*detection.DetectionResult, error)
- func (img *Image) Fill(width, height int, anchor Anchor, filter ResampleFilter) *Image
- func (img *Image) Fit(width, height int, filter ResampleFilter) *Image
- func (img *Image) FlipH() *Image
- func (img *Image) FlipV() *Image
- func (img *Image) GetMetadata() *ProcessingMetadata
- func (img *Image) Grayscale() *Image
- func (img *Image) Invert() *Image
- func (img *Image) Overlay(src *Image, pos image.Point, opacity float64) *Image
- func (img *Image) OverlayCenter(src *Image, opacity float64) *Image
- func (img *Image) Paste(src *Image, pos image.Point) *Image
- func (img *Image) PasteCenter(src *Image) *Image
- func (img *Image) Resize(width, height int, filter ResampleFilter) *Image
- func (img *Image) Rotate(angle float64, bgColor color.Color) *Image
- func (img *Image) Rotate180() *Image
- func (img *Image) Rotate270() *Image
- func (img *Image) Rotate90() *Image
- func (img *Image) Save(path string, opts ...SaveOption) error
- func (img *Image) SetAuthor(author string) *Image
- func (img *Image) Sharpen(sigma float64) *Image
- func (img *Image) Thumbnail(width, height int, filter ResampleFilter) *Image
- func (img *Image) ToNRGBA() *image.NRGBA
- func (img *Image) Transpose() *Image
- func (img *Image) Transverse() *Image
- func (img *Image) Watermark(opts WatermarkOptions) *Image
- type ImageMetadata
- type MetadataOption
- type OperationRecord
- type Options
- type ProcessingMetadata
- type ResampleFilter
- type SaveConfig
- type SaveOption
- type WatermarkOptions
Examples ¶
Constants ¶
const Author = "razzkumar"
Author is the default author for imgx
const ProjectURL = "https://github.com/razzkumar/imgx"
ProjectURL is the GitHub URL of the project
const Version = "1.2.2"
Version is the current version of imgx This is the single source of truth for versioning Update this when releasing new versions
Variables ¶
var ErrUnsupportedFormat = errors.New("imaging: unsupported image format")
ErrUnsupportedFormat means the given image format is not supported.
Functions ¶
func AdjustBrightness ¶
AdjustBrightness changes the brightness of the image using the percentage parameter and returns the adjusted image. The percentage must be in range (-100, 100). The percentage = 0 gives the original image. The percentage = -100 gives solid black image. The percentage = 100 gives solid white image.
Examples:
dstImage = imaging.AdjustBrightness(srcImage, -15) // Decrease image brightness by 15%. dstImage = imaging.AdjustBrightness(srcImage, 10) // Increase image brightness by 10%.
func AdjustContrast ¶
AdjustContrast changes the contrast of the image using the percentage parameter and returns the adjusted image. The percentage must be in range (-100, 100). The percentage = 0 gives the original image. The percentage = -100 gives solid gray image.
Examples:
dstImage = imaging.AdjustContrast(srcImage, -10) // Decrease image contrast by 10%. dstImage = imaging.AdjustContrast(srcImage, 20) // Increase image contrast by 20%.
func AdjustFunc ¶
AdjustFunc applies the fn function to each pixel of the img image and returns the adjusted image.
Example:
dstImage = imaging.AdjustFunc(
srcImage,
func(c color.NRGBA) color.NRGBA {
// Shift the red channel by 16.
r := int(c.R) + 16
if r > 255 {
r = 255
}
return color.NRGBA{uint8(r), c.G, c.B, c.A}
}
)
func AdjustGamma ¶
AdjustGamma performs a gamma correction on the image and returns the adjusted image. Gamma parameter must be positive. Gamma = 1.0 gives the original image. Gamma less than 1.0 darkens the image and gamma greater than 1.0 lightens it.
Example:
dstImage = imaging.AdjustGamma(srcImage, 0.7)
func AdjustHue ¶
AdjustHue changes the hue of the image using the shift parameter (measured in degrees) and returns the adjusted image. The shift = 0 (or 360 / -360 / etc.) gives the original image. The shift = 180 (or -180) corresponds to a 180° degree rotation of the color wheel and thus gives the image with its hue inverted for each pixel.
Examples:
dstImage = imaging.AdjustHue(srcImage, 90) // Shift Hue by 90°. dstImage = imaging.AdjustHue(srcImage, -30) // Shift Hue by -30°.
func AdjustSaturation ¶
AdjustSaturation changes the saturation of the image using the percentage parameter and returns the adjusted image. The percentage must be in the range (-100, 100). The percentage = 0 gives the original image. The percentage = 100 gives the image with the saturation value doubled for each pixel. The percentage = -100 gives the image with the saturation value zeroed for each pixel (grayscale).
Examples:
dstImage = imaging.AdjustSaturation(srcImage, 25) // Increase image saturation by 25%. dstImage = imaging.AdjustSaturation(srcImage, -10) // Decrease image saturation by 10%.
func AdjustSigmoid ¶
AdjustSigmoid changes the contrast of the image using a sigmoidal function and returns the adjusted image. It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. The midpoint parameter is the midpoint of contrast that must be between 0 and 1, typically 0.5. The factor parameter indicates how much to increase or decrease the contrast, typically in range (-10, 10). If the factor parameter is positive the image contrast is increased otherwise the contrast is decreased.
Examples:
dstImage = imaging.AdjustSigmoid(srcImage, 0.5, 3.0) // Increase the contrast. dstImage = imaging.AdjustSigmoid(srcImage, 0.5, -3.0) // Decrease the contrast.
func Blur ¶
Blur produces a blurred version of the image using a Gaussian function. Sigma parameter must be positive and indicates how much the image will be blurred.
Example:
dstImage := imaging.Blur(srcImage, 3.5)
func Convolve3x3 ¶
Convolve3x3 convolves the image with the specified 3x3 convolution kernel. Default parameters are used if a nil *ConvolveOptions is passed.
func Convolve5x5 ¶
Convolve5x5 convolves the image with the specified 5x5 convolution kernel. Default parameters are used if a nil *ConvolveOptions is passed.
func Crop ¶
Crop cuts out a rectangular region with the specified bounds from the image and returns the cropped image.
func CropAnchor ¶
CropAnchor cuts out a rectangular region with the specified size from the image using the specified anchor point and returns the cropped image.
func CropCenter ¶
CropCenter cuts out a rectangular region with the specified size from the center of the image and returns the cropped image.
func Encode ¶
Encode writes the image img to w in the specified format (JPEG, PNG, GIF, TIFF or BMP).
func Fill ¶
Fill creates an image with the specified dimensions and fills it with the scaled source image. To achieve the correct aspect ratio without stretching, the source image will be cropped.
Example:
dstImage := imaging.Fill(srcImage, 800, 600, imaging.Center, imaging.Lanczos)
func Fit ¶
Fit scales down the image using the specified resample filter to fit the specified maximum width and height and returns the transformed image.
Example:
dstImage := imaging.Fit(srcImage, 800, 600, imaging.Lanczos)
func FlipH ¶
FlipH flips the image horizontally (from left to right) and returns the transformed image.
func FlipV ¶
FlipV flips the image vertically (from top to bottom) and returns the transformed image.
func GetAddMetadata ¶ added in v1.0.0
func GetAddMetadata() bool
GetAddMetadata returns the global metadata setting
func GetDefaultAuthor ¶ added in v1.0.0
func GetDefaultAuthor() string
GetDefaultAuthor returns the global default author setting
func Histogram ¶
Histogram returns a normalized histogram of an image.
Resulting histogram is represented as an array of 256 floats, where histogram[i] is a probability of a pixel being of a particular luminance i.
func New ¶
New creates a new image with the specified width and height, and fills it with the specified color.
func Overlay ¶
Overlay draws the img image over the background image at given position and returns the combined image. Opacity parameter is the opacity of the img image layer, used to compose the images, it must be from 0.0 to 1.0.
Examples:
// Draw spriteImage over backgroundImage at the given position (x=50, y=50). dstImage := imaging.Overlay(backgroundImage, spriteImage, image.Pt(50, 50), 1.0) // Blend two opaque images of the same size. dstImage := imaging.Overlay(imageOne, imageTwo, image.Pt(0, 0), 0.5)
func OverlayCenter ¶
OverlayCenter overlays the img image to the center of the background image and returns the combined image. Opacity parameter is the opacity of the img image layer, used to compose the images, it must be from 0.0 to 1.0.
func Paste ¶
Paste pastes the img image to the background image at the specified position and returns the combined image.
func PasteCenter ¶
PasteCenter pastes the img image to the center of the background image and returns the combined image.
func Resize ¶
Resize resizes the image to the specified width and height using the specified resampling filter and returns the transformed image. If one of width or height is 0, the image aspect ratio is preserved.
Example:
dstImage := imaging.Resize(srcImage, 800, 600, imaging.Lanczos)
func Rotate ¶
Rotate rotates an image by the given angle counter-clockwise . The angle parameter is the rotation angle in degrees. The bgColor parameter specifies the color of the uncovered zone after the rotation.
func Rotate180 ¶
Rotate180 rotates the image 180 degrees counter-clockwise and returns the transformed image.
func Rotate270 ¶
Rotate270 rotates the image 270 degrees counter-clockwise and returns the transformed image.
func Rotate90 ¶
Rotate90 rotates the image 90 degrees counter-clockwise and returns the transformed image.
func SetAddMetadata ¶ added in v1.0.0
func SetAddMetadata(enabled bool)
SetAddMetadata configures whether to add metadata globally
func SetDefaultAuthor ¶ added in v1.0.0
func SetDefaultAuthor(author string)
SetDefaultAuthor sets the default artist/creator name globally This can be overridden per-image using WithAuthor() or SetAuthor() Empty string means use the default "razzkumar"
func SetMaxProcs ¶
func SetMaxProcs(value int)
SetMaxProcs limits the number of concurrent processing goroutines to the given value. A value <= 0 clears the limit.
func Sharpen ¶
Sharpen produces a sharpened version of the image. Sigma parameter must be positive and indicates how much the image will be sharpened.
Example:
dstImage := imaging.Sharpen(srcImage, 3.5)
func Thumbnail ¶
Thumbnail scales the image up or down using the specified resample filter, crops it to the specified width and hight and returns the transformed image.
Example:
dstImage := imaging.Thumbnail(srcImage, 100, 100, imaging.Lanczos)
func Transverse ¶
Transverse flips the image vertically and rotates 90 degrees counter-clockwise.
func Watermark ¶
func Watermark(img image.Image, opts WatermarkOptions) *image.NRGBA
Watermark adds a text watermark to an image and returns the result.
Example:
opts := imaging.WatermarkOptions{
Text: "Copyright 2025",
Position: imaging.BottomRight,
Opacity: 0.5,
}
watermarkedImage := imaging.Watermark(srcImage, opts)
Types ¶
type Config ¶ added in v1.0.0
type Config struct {
AddMetadata bool
DefaultAuthor string
// contains filtered or unexported fields
}
Config holds global configuration for imgx
type ConvolveOptions ¶
type ConvolveOptions struct {
// If Normalize is true the kernel is normalized before convolution.
Normalize bool
// If Abs is true the absolute value of each color channel is taken after convolution.
Abs bool
// Bias is added to each color channel value after convolution.
Bias int
}
ConvolveOptions are convolution parameters.
type DecodeOption ¶
type DecodeOption func(*decodeConfig)
DecodeOption sets an optional parameter for the Decode and Open functions.
func AutoOrientation ¶
func AutoOrientation(enabled bool) DecodeOption
AutoOrientation returns a DecodeOption that sets the auto-orientation mode. If auto-orientation is enabled, the image will be transformed after decoding according to the EXIF orientation tag (if present). By default it's disabled.
type EncodeOption ¶
type EncodeOption func(*encodeConfig)
EncodeOption sets an optional parameter for the Encode and Save functions.
func GIFDrawer ¶
func GIFDrawer(drawer draw.Drawer) EncodeOption
GIFDrawer returns an EncodeOption that sets the drawer that is used to convert the source image to the desired palette of the GIF-encoded image.
func GIFNumColors ¶
func GIFNumColors(numColors int) EncodeOption
GIFNumColors returns an EncodeOption that sets the maximum number of colors used in the GIF-encoded image. It ranges from 1 to 256. Default is 256.
func GIFQuantizer ¶
func GIFQuantizer(quantizer draw.Quantizer) EncodeOption
GIFQuantizer returns an EncodeOption that sets the quantizer that is used to produce a palette of the GIF-encoded image.
func JPEGQuality ¶
func JPEGQuality(quality int) EncodeOption
JPEGQuality returns an EncodeOption that sets the output JPEG quality. Quality ranges from 1 to 100 inclusive, higher is better. Default is 95.
func PNGCompressionLevel ¶
func PNGCompressionLevel(level png.CompressionLevel) EncodeOption
PNGCompressionLevel returns an EncodeOption that sets the compression level of the PNG-encoded image. Default is png.DefaultCompression.
type Format ¶
type Format int
Format is an image file format.
func FormatFromExtension ¶
FormatFromExtension parses image format from filename extension: "jpg" (or "jpeg"), "png", "gif", "tif" (or "tiff") and "bmp" are supported.
func FormatFromFilename ¶
FormatFromFilename parses image format from filename: "jpg" (or "jpeg"), "png", "gif", "tif" (or "tiff") and "bmp" are supported.
type Image ¶ added in v1.0.0
type Image struct {
// contains filtered or unexported fields
}
Image represents an image with processing metadata
func FromImage ¶ added in v1.0.0
FromImage creates an Image instance from an existing image.Image Optionally pass Options to configure metadata
Examples:
img := imgx.FromImage(stdImg) // use defaults
img := imgx.FromImage(stdImg, imgx.Options{Author: "Jane Doe"})
func Load ¶ added in v1.0.0
Load loads an image from a file path and returns an Image instance Optionally pass Options to configure loading behavior
Examples:
img, err := imgx.Load("photo.jpg") // use defaults
img, err := imgx.Load("photo.jpg", imgx.Options{AutoOrient: true})
img, err := imgx.Load("photo.jpg", imgx.Options{Author: "John Doe"})
func NewImage ¶ added in v1.0.0
NewImage creates a new blank Image with the specified dimensions and fill color Optionally pass Options to configure metadata
Examples:
img := imgx.NewImage(800, 600, color.White) // use defaults
img := imgx.NewImage(800, 600, color.White, imgx.Options{Author: "Bob"})
func (*Image) AdjustBrightness ¶ added in v1.0.0
AdjustBrightness adjusts the brightness of the image
func (*Image) AdjustContrast ¶ added in v1.0.0
AdjustContrast adjusts the contrast of the image
func (*Image) AdjustGamma ¶ added in v1.0.0
AdjustGamma adjusts the gamma of the image
func (*Image) AdjustSaturation ¶ added in v1.0.0
AdjustSaturation adjusts the saturation of the image
func (*Image) AdjustSigmoid ¶ added in v1.0.0
AdjustSigmoid applies a sigmoid function to the image
func (*Image) Convolve3x3 ¶ added in v1.0.0
func (img *Image) Convolve3x3(kernel [9]float64, options *ConvolveOptions) *Image
Convolve3x3 applies a 3x3 convolution kernel to the image
func (*Image) Convolve5x5 ¶ added in v1.0.0
func (img *Image) Convolve5x5(kernel [25]float64, options *ConvolveOptions) *Image
Convolve5x5 applies a 5x5 convolution kernel to the image
func (*Image) CropAnchor ¶ added in v1.0.0
CropAnchor cuts out a rectangular region with the specified size using the anchor point
func (*Image) CropCenter ¶ added in v1.0.0
CropCenter cuts out a rectangular region from the center of the image
func (*Image) Detect ¶ added in v1.1.0
func (img *Image) Detect(ctx context.Context, provider string, opts ...*detection.DetectOptions) (*detection.DetectionResult, error)
Detect performs object detection on the image using the specified provider and returns detection results.
Supported providers:
- "ollama" or "gemma3" - Local Ollama server (default, uses gemma3 model)
- "gemini" or "google" - Google Gemini API (requires GEMINI_API_KEY)
- "aws" - AWS Rekognition (uses AWS credential chain: env vars, ~/.aws/credentials, IAM roles, etc.)
- "openai" - OpenAI Vision (requires OPENAI_API_KEY)
Example:
img, err := imgx.Load("photo.jpg")
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
result, err := img.Detect(ctx, "ollama")
if err != nil {
log.Fatal(err)
}
// Access detection results
for _, label := range result.Labels {
fmt.Printf("Found: %s (%.2f%% confidence)\n", label.Name, label.Confidence*100)
}
With custom options:
opts := &detection.DetectOptions{
Features: []detection.Feature{detection.FeatureLabels, detection.FeatureText},
MaxResults: 15,
MinConfidence: 0.7,
CustomPrompt: "Is there a dog in this image?",
}
result, err := img.Detect(ctx, "ollama", opts)
func (*Image) Fill ¶ added in v1.0.0
func (img *Image) Fill(width, height int, anchor Anchor, filter ResampleFilter) *Image
Fill resizes and crops the image to fill the specified dimensions using the specified anchor point.
func (*Image) Fit ¶ added in v1.0.0
func (img *Image) Fit(width, height int, filter ResampleFilter) *Image
Fit scales the image down to fit within the specified maximum width and height while preserving aspect ratio.
func (*Image) GetMetadata ¶ added in v1.0.0
func (img *Image) GetMetadata() *ProcessingMetadata
GetMetadata returns the processing metadata
func (*Image) Overlay ¶ added in v1.0.0
Overlay overlays another image on top of this image with the specified opacity
func (*Image) OverlayCenter ¶ added in v1.0.0
OverlayCenter overlays another image at the center with the specified opacity
func (*Image) Paste ¶ added in v1.0.0
Paste pastes another image onto this image at the specified position
func (*Image) PasteCenter ¶ added in v1.0.0
PasteCenter pastes another image at the center of this image
func (*Image) Resize ¶ added in v1.0.0
func (img *Image) Resize(width, height int, filter ResampleFilter) *Image
Resize resizes the image to the specified width and height using the specified resampling filter. If width or height is 0, it will be calculated to preserve the aspect ratio.
func (*Image) Rotate ¶ added in v1.0.0
Rotate rotates the image by the given angle counter-clockwise. The angle parameter is the rotation angle in degrees. The bgColor parameter specifies the color of the uncovered areas after rotation.
func (*Image) Rotate270 ¶ added in v1.0.0
Rotate270 rotates the image 270° counter-clockwise (90° clockwise)
func (*Image) Save ¶ added in v1.0.0
func (img *Image) Save(path string, opts ...SaveOption) error
Save saves the image to the specified path with optional metadata injection
func (*Image) SetAuthor ¶ added in v1.0.0
SetAuthor sets the artist/creator name for the image metadata This overrides the default author but keeps creator_tool unchanged
func (*Image) Thumbnail ¶ added in v1.0.0
func (img *Image) Thumbnail(width, height int, filter ResampleFilter) *Image
Thumbnail creates a square thumbnail by cropping and resizing the image.
func (*Image) Transpose ¶ added in v1.0.0
Transpose flips the image horizontally and rotates 90° counter-clockwise
func (*Image) Transverse ¶ added in v1.0.0
Transverse flips the image vertically and rotates 90° counter-clockwise
func (*Image) Watermark ¶ added in v1.0.0
func (img *Image) Watermark(opts WatermarkOptions) *Image
Watermark adds a text watermark to the image
type ImageMetadata ¶ added in v1.0.0
type ImageMetadata struct {
// File Information
FilePath string `json:"file_path"`
FileName string `json:"file_name"`
Format string `json:"format"`
ContentType string `json:"content_type"` // MIME type (e.g., "image/jpeg", "image/png")
FileSize int64 `json:"file_size"`
// Image Properties
Width int `json:"width"`
Height int `json:"height"`
AspectRatio string `json:"aspect_ratio"` // Formatted as "16:9" (Width:Height)
Megapixels float64 `json:"megapixels"`
ColorModel string `json:"color_model"`
Orientation int `json:"orientation,omitempty"`
// Image Technical Details
BitDepth int `json:"bit_depth,omitempty"`
ColorSpace string `json:"color_space,omitempty"`
Compression string `json:"compression,omitempty"`
XResolution float64 `json:"x_resolution,omitempty"`
YResolution float64 `json:"y_resolution,omitempty"`
ResolutionUnit string `json:"resolution_unit,omitempty"`
ImageDescription string `json:"image_description,omitempty"`
UserComment string `json:"user_comment,omitempty"`
// Extended Metadata
Extended map[string]any `json:"extended,omitempty"`
HasExtended bool `json:"has_extended"`
// Camera Information
CameraMake string `json:"camera_make,omitempty"`
CameraModel string `json:"camera_model,omitempty"`
CameraSerialNumber string `json:"camera_serial_number,omitempty"`
LensMake string `json:"lens_make,omitempty"`
LensModel string `json:"lens_model,omitempty"`
LensSerialNumber string `json:"lens_serial_number,omitempty"`
LensFocalLengthMin string `json:"lens_focal_length_min,omitempty"`
LensFocalLengthMax string `json:"lens_focal_length_max,omitempty"`
FirmwareVersion string `json:"firmware_version,omitempty"`
// Camera Settings
FocalLength string `json:"focal_length,omitempty"`
Aperture string `json:"aperture,omitempty"` // F-number
ShutterSpeed string `json:"shutter_speed,omitempty"`
ISO string `json:"iso,omitempty"`
ExposureCompensation string `json:"exposure_compensation,omitempty"`
ExposureMode string `json:"exposure_mode,omitempty"`
ExposureProgram string `json:"exposure_program,omitempty"`
MeteringMode string `json:"metering_mode,omitempty"`
WhiteBalance string `json:"white_balance,omitempty"`
Flash string `json:"flash,omitempty"`
FlashMode string `json:"flash_mode,omitempty"`
LightSource string `json:"light_source,omitempty"`
SceneCaptureType string `json:"scene_capture_type,omitempty"`
SubjectDistance string `json:"subject_distance,omitempty"`
FocusMode string `json:"focus_mode,omitempty"`
DigitalZoomRatio string `json:"digital_zoom_ratio,omitempty"`
// Timestamps
DateTime string `json:"date_time,omitempty"`
DateTimeOriginal string `json:"date_time_original,omitempty"`
DateTimeDigitized string `json:"date_time_digitized,omitempty"`
CreateDate string `json:"create_date,omitempty"`
ModifyDate string `json:"modify_date,omitempty"`
TimeZone string `json:"time_zone,omitempty"`
// GPS Location
GPSLatitude string `json:"gps_latitude,omitempty"`
GPSLongitude string `json:"gps_longitude,omitempty"`
GPSAltitude string `json:"gps_altitude,omitempty"`
GPSTimestamp string `json:"gps_timestamp,omitempty"`
GPSSpeed string `json:"gps_speed,omitempty"`
GPSDirection string `json:"gps_direction,omitempty"`
GPSSatellites string `json:"gps_satellites,omitempty"`
GPSDatum string `json:"gps_datum,omitempty"`
// Content & Authorship
Title string `json:"title,omitempty"`
Subject string `json:"subject,omitempty"`
Keywords string `json:"keywords,omitempty"`
Rating int `json:"rating,omitempty"`
Artist string `json:"artist,omitempty"`
Copyright string `json:"copyright,omitempty"`
Creator string `json:"creator,omitempty"`
CreatorTool string `json:"creator_tool,omitempty"`
Software string `json:"software,omitempty"`
}
ImageMetadata contains comprehensive image metadata information
func Metadata ¶ added in v1.0.0
func Metadata(src string, options ...MetadataOption) (*ImageMetadata, error)
Metadata extracts metadata from an image file. If exiftool is available on the system, returns comprehensive EXIF/IPTC/XMP data. Otherwise, returns basic metadata extracted using Go's image package.
Example:
metadata, err := imgx.Metadata("photo.jpg")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Dimensions: %dx%d\n", metadata.Width, metadata.Height)
if metadata.HasExtended {
fmt.Printf("Camera: %s\n", metadata.CameraMake)
}
type MetadataOption ¶ added in v1.0.0
type MetadataOption func(*metadataConfig)
MetadataOption configures metadata extraction
func WithBasicOnly ¶ added in v1.0.0
func WithBasicOnly() MetadataOption
WithBasicOnly forces basic metadata extraction only (skip exiftool check)
type OperationRecord ¶ added in v1.0.0
OperationRecord represents a single image processing operation
type Options ¶ added in v1.0.0
type Options struct {
// AutoOrient enables automatic orientation correction based on EXIF data
AutoOrient bool
// DisableMetadata disables metadata tracking for this image instance
DisableMetadata bool
// Author sets a custom artist/creator name for the image metadata
// Empty string uses the default author
Author string
}
Options holds configuration for loading and processing images
type ProcessingMetadata ¶ added in v1.0.0
type ProcessingMetadata struct {
SourcePath string
Operations []OperationRecord
Software string // Fixed: "imgx"
Version string // Fixed: version from load.go
Author string // Customizable: artist/creator name
ProjectURL string // Fixed: project URL
AddMetadata bool
DetectionResult *detection.DetectionResult `json:"detection_result,omitempty"` // Object detection results
}
ProcessingMetadata contains information about image processing operations
func (*ProcessingMetadata) AddOperation ¶ added in v1.0.0
func (m *ProcessingMetadata) AddOperation(action, parameters string)
AddOperation adds a new operation record to the metadata
func (*ProcessingMetadata) Clone ¶ added in v1.0.0
func (m *ProcessingMetadata) Clone() *ProcessingMetadata
Clone creates a deep copy of ProcessingMetadata
type ResampleFilter ¶
ResampleFilter specifies a resampling filter to be used for image resizing.
General filter recommendations: - Lanczos A high-quality resampling filter for photographic images yielding sharp results. - CatmullRom A sharp cubic filter that is faster than Lanczos filter while providing similar results. - MitchellNetravali A cubic filter that produces smoother results with less ringing artifacts than CatmullRom. - Linear Bilinear resampling filter, produces a smooth output. Faster than cubic filters. - Box Simple and fast averaging filter appropriate for downscaling. When upscaling it's similar to NearestNeighbor. - NearestNeighbor Fastest resampling filter, no antialiasing.
var BSpline ResampleFilter
BSpline is a smooth cubic filter (BC-spline; B=1; C=0).
var Bartlett ResampleFilter
Bartlett is a Bartlett-windowed sinc filter (3 lobes).
var Blackman ResampleFilter
Blackman is a Blackman-windowed sinc filter (3 lobes).
var Box ResampleFilter
Box filter (averaging pixels).
var CatmullRom ResampleFilter
CatmullRom is a Catmull-Rom - sharp cubic filter (BC-spline; B=0; C=0.5).
var Cosine ResampleFilter
Cosine is a Cosine-windowed sinc filter (3 lobes).
var Gaussian ResampleFilter
Gaussian is a Gaussian blurring filter.
var Hamming ResampleFilter
Hamming is a Hamming-windowed sinc filter (3 lobes).
var Hann ResampleFilter
Hann is a Hann-windowed sinc filter (3 lobes).
var Hermite ResampleFilter
Hermite cubic spline filter (BC-spline; B=0; C=0).
var Lanczos ResampleFilter
Lanczos filter (3 lobes).
var Linear ResampleFilter
Linear filter.
var MitchellNetravali ResampleFilter
MitchellNetravali is Mitchell-Netravali cubic filter (BC-spline; B=1/3; C=1/3).
var NearestNeighbor ResampleFilter
NearestNeighbor is a nearest-neighbor filter (no anti-aliasing).
var Welch ResampleFilter
Welch is a Welch-windowed sinc filter (parabolic window, 3 lobes).
type SaveConfig ¶ added in v1.0.0
type SaveConfig struct {
DisableMetadata bool
JPEGQuality int
PNGCompression png.CompressionLevel
GIFNumColors int
}
SaveConfig holds configuration for saving images
type SaveOption ¶ added in v1.0.0
type SaveOption func(*SaveConfig)
SaveOption configures image saving
func WithGIFNumColors ¶ added in v1.0.0
func WithGIFNumColors(numColors int) SaveOption
WithGIFNumColors sets the number of colors for GIF encoding
func WithJPEGQuality ¶ added in v1.0.0
func WithJPEGQuality(quality int) SaveOption
WithJPEGQuality sets the JPEG quality (1-100)
func WithPNGCompression ¶ added in v1.0.0
func WithPNGCompression(level png.CompressionLevel) SaveOption
WithPNGCompression sets the PNG compression level
func WithoutMetadata ¶ added in v1.0.0
func WithoutMetadata() SaveOption
WithoutMetadata disables metadata writing for this save operation
type WatermarkOptions ¶
type WatermarkOptions struct {
// Text is the watermark text to be rendered on the image.
Text string
// Position specifies where to place the watermark (e.g., BottomRight, TopLeft).
// Default is BottomRight.
Position Anchor
// Opacity controls the transparency of the watermark text (0.0 to 1.0).
// 0.0 is fully transparent, 1.0 is fully opaque.
// Default is 0.5 (50% opacity).
Opacity float64
// TextColor is the color of the watermark text.
// Default is white (255, 255, 255).
TextColor color.Color
// Font is the font face to use for rendering the text.
// If nil, basicfont.Face7x13 is used as default.
Font font.Face
// Padding is the number of pixels to offset from the edge based on Position.
// Default is 10 pixels.
Padding int
}
WatermarkOptions contains options for adding a text watermark to an image.











