imagewatermark

package module
v3.0.0 Latest Latest
Warning

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

Go to latest
Published: Feb 17, 2026 License: MIT Imports: 9 Imported by: 0

README

🧊 Go Image Watermarking Package

This Go package provides a simple and configurable way to overlay watermarks on images. It lets you control watermark opacity, size, alignment and rotation.

Supports both single watermark placement and grid patterns with full customization options and support also for batch processing multiple images concurrently.


⬇️ Installation

go get github.com/filipenevs/go-imagewatermark/v3

📄 Quick Start

Single Watermark Example
package main

import (
    "log"
    "github.com/filipenevs/go-imagewatermark/v3"
)

func main() {
    inputImg, inputErr := imagewatermark.OpenImage("input.jpg")
    if inputErr != nil {
        log.Fatal(inputErr)
    }

    watermarkImg, watermarkErr := imagewatermark.OpenImage("logo.png")
    if watermarkErr != nil {
        log.Fatal(watermarkErr)
    }

    config := imagewatermark.SingleConfig{
        GeneralConfig: imagewatermark.GeneralConfig{
            WatermarkWidthPercent: 20,
            OpacityAlpha:          0.5,
        },
        VerticalAlign:   imagewatermark.VerticalBottom,
        HorizontalAlign: imagewatermark.HorizontalRight,
        Spacing:         30,
    }

    result, err := imagewatermark.ApplySingle(inputImg, watermarkImg, config)
    if err != nil {
        log.Fatal(err)
    }
}
output_image_example_1
Grid Watermark Example
package main

import (
    "log"
    "github.com/filipenevs/go-imagewatermark/v3"
)

func main() {
    inputImg, inputErr := imagewatermark.OpenImage("input.jpg")
    if inputErr != nil {
        log.Fatal(inputErr)
    }

    watermarkImg, watermarkErr := imagewatermark.OpenImage("logo.png")
    if watermarkErr != nil {
        log.Fatal(watermarkErr)
    }

    config := imagewatermark.GridConfig{
        GeneralConfig: imagewatermark.GeneralConfig{
            WatermarkWidthPercent: 10,
            OpacityAlpha:          0.3,
            RotationDegrees:       45,
        },
        GridSpacingX: 40,
        GridSpacingY: 40,
        OffsetX:      -15,
        OffsetY:      -15,
    }

    result, err := imagewatermark.ApplyGrid(inputImg, watermarkImg, config)
    if err != nil {
        log.Fatal(err)
    }
}
output_image_example_2

⚙️ Config

General Configuration

The GeneralConfig struct contains common settings for all watermarking operations:

Field Type Description Range
OpacityAlpha float64 Transparency level of the watermark (0.0 - 1.0]
WatermarkWidthPercent float64 Watermark width as percentage of input image (0 - 100]
RotationDegrees float64 Rotation angle for the watermark [0 - 360]
ResampleFilter imaging.ResampleFilter Resampling filter used for resizing the watermark Any valid imaging.ResampleFilter
MaxWorkers int Maximum number of concurrent workers for batch processing (Default is number of CPU cores) Non-negative integer
Single Watermark Configuration

The SingleConfig extends GeneralConfig with alignment options:

Field Type Description Options
VerticalAlign VerticalAlign Vertical alignment position VerticalTop, VerticalMiddle, VerticalBottom, VerticalRandom
HorizontalAlign HorizontalAlign Horizontal alignment position HorizontalLeft, HorizontalMiddle, HorizontalRight, HorizontalRandom
Spacing int Distance from aligned edge (pixels) Any non-negative integer

Example:

config := imagewatermark.SingleConfig{
    GeneralConfig: imagewatermark.GeneralConfig{
        WatermarkWidthPercent: 20,
        OpacityAlpha:          0.7,
        RotationDegrees:       0,
    },
    VerticalAlign:   imagewatermark.VerticalBottom,
    HorizontalAlign: imagewatermark.HorizontalRight,
    Spacing:         15,
}
Grid Watermark Configuration

The GridConfig extends GeneralConfig with grid-specific options:

Field Type Description Notes
GridSpacingX int Horizontal spacing between watermarks (pixels) Can be negative for overlapping
GridSpacingY int Vertical spacing between watermarks (pixels) Can be negative for overlapping
OffsetX int Initial horizontal offset for grid start (pixels) Can be negative to shift grid left
OffsetY int Initial vertical offset for grid start (pixels) Can be negative to shift grid up

Example:

config := imagewatermark.GridConfig{
    GeneralConfig: imagewatermark.GeneralConfig{
        WatermarkWidthPercent: 10,
        OpacityAlpha:          0.3,
        RotationDegrees:       0,
    },
    GridSpacingX: 200,
    GridSpacingY: 200,
    OffsetX:      -50,
    OffsetY:      -50,
}

🧠 Advanced Examples

Random Placement
config := imagewatermark.SingleConfig{
    GeneralConfig: imagewatermark.GeneralConfig{
        WatermarkWidthPercent: 15,
        OpacityAlpha:          0.5,
        RotationDegrees:       0,
    },
    VerticalAlign:   imagewatermark.VerticalRandom,   // Random vertically
    HorizontalAlign: imagewatermark.HorizontalRandom, // Random horizontally
}
Rotated Grid Pattern
config := imagewatermark.GridConfig{
    GeneralConfig: imagewatermark.GeneralConfig{
        WatermarkWidthPercent: 8,
        OpacityAlpha:          0.25,
        RotationDegrees:       45, // Rotate watermarks 45 degrees
    },
    GridSpacingX: 250,
    GridSpacingY: 250,
    OffsetX:      -75,
    OffsetY:      -75,
}
Custom Resampling Filter
config := imagewatermark.SingleConfig{
    GeneralConfig: imagewatermark.GeneralConfig{
        WatermarkWidthPercent: 20,
        OpacityAlpha:          0.5,
        RotationDegrees:       0,
        ResampleFilter:        imaging.Lanczos, // Use Lanczos filter for high-quality resizing
    },
    VerticalAlign:   imagewatermark.VerticalBottom,
    HorizontalAlign: imagewatermark.HorizontalRight,
    Spacing:         30,
}
Batch Processing Multiple Images
cfg := imagewatermark.GridConfig{
    GeneralConfig: imagewatermark.GeneralConfig{
        OpacityAlpha:          0.3,
        WatermarkWidthPercent: 10,
        RotationDegrees:       10,
        MaxWorkers:            4, // Limit to 4 concurrent workers for batch processing
    },
    GridSpacingX: 40,
    GridSpacingY: 40,
    OffsetX:      -15,
    OffsetY:      -15,
}

newImgs, err := imagewatermark.BatchApplyGrid([]image.Image{inputImg1, inputImg2}, watermarkImg, cfg)

Error Handling

The library provides detailed error messages for common issues:

result, err := imagewatermark.ApplySingle(inputImg, watermarkImg, config)
if err != nil {
    log.Printf("Error: %v", err)
    // Possible errors:
    // - "invalid watermark configuration: ..."
    // - "failed to load input image: ..."
    // - "failed to load watermark image: ..."
}

📜 License

MIT License. See LICENSE file for details.


🤝 Contributing

Pull requests and issues are welcome!

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ApplyGrid

func ApplyGrid(
	inputImg image.Image,
	watermarkImg image.Image,
	config GridConfig,
) (image.Image, error)

ApplyGrid applies a grid pattern of watermarks to an input image based on the provided configuration.

The function performs the following steps:

  1. Validates the GridConfig.
  2. Preprocesses the watermark (resize, rotate, and apply opacity).
  3. Generates grid positions based on spacing and offset settings.
  4. Applies the watermark at each grid position.
  5. Returns the final image with the grid watermarks applied.

The parallel image loading uses goroutines to improve performance for I/O operations. If the offset or spacing values are negative, the grid pattern will be shifted or compressed accordingly.

Parameters:

  • inputImg: The input image to which the grid watermark will be applied.
  • watermarkImg: The watermark image to overlay on the input image.
  • config: GridConfig struct containing spacing, offset, and watermark appearance settings.

Returns:

  • An image.Image containing the final image with the grid watermark pattern applied.
  • An error if configuration is invalid or image loading fails.

Example:

config := GridConfig{
	GeneralConfig: GeneralConfig{
		WatermarkWidthPercent: 20,
		OpacityAlpha:          0.5,
		RotationDegrees:       45,
	},
	GridSpacingX: 75,
	GridSpacingY: 75,
	OffsetX:      -50,
	OffsetY:      -50,
}
result, err := ApplyGrid(config)
if err != nil {
	log.Fatal(err)
}

func ApplySingle

func ApplySingle(
	inputImg image.Image,
	watermarkImg image.Image,
	config SingleConfig,
) (image.Image, error)

ApplySingle overlays a single watermark onto an input image at a specific position based on the provided configuration.

The function performs the following steps:

  1. Validates the SingleConfig to ensure all settings are valid.
  2. Preprocesses the watermark (resize, rotate, and apply opacity).
  3. Calculates the watermark position based on vertical/horizontal alignment and spacing.
  4. Creates an RGBA copy of the input image.
  5. Overlays the watermark onto the input image using the "Over" compositing operator.

Parameters:

  • inputImg: The input image to which the watermark will be applied.
  • watermarkImg: The watermark image to overlay on the input image.
  • config: SingleConfig struct containing opacity, size, alignment, and rotation settings.

Returns:

  • An image.Image containing the final image with the watermark applied.
  • An error if any step fails, such as invalid configuration or failure to load images.

Example:

config := SingleConfig{
	GeneralConfig: GeneralConfig{
		WatermarkWidthPercent: 20,
		OpacityAlpha:          0.6,
		RotationDegrees:       0,
	},
	VerticalAlign:   VerticalBottom,
	HorizontalAlign: HorizontalRight,
	Spacing:         10,
}
result, err := ApplySingle(inputImg, watermarkImg, config)
if err != nil {
	log.Fatal(err)
}

func BatchApplyGrid

func BatchApplyGrid(
	inputImgs []image.Image,
	watermarkImg image.Image,
	config GridConfig,
) ([]image.Image, error)

func BatchApplySingle

func BatchApplySingle(
	inputImgs []image.Image,
	watermarkImg image.Image,
	config SingleConfig,
) ([]image.Image, error)

BatchApplySingle applies a single watermark to a batch of input images concurrently based on the provided configuration.

This function performs the following steps:

  1. Validates the SingleConfig to ensure all settings are valid.
  2. Preprocesses the watermark (rotate and apply opacity) once for efficiency.
  3. Uses a worker pool to process multiple images concurrently, applying the watermark to each image.
  4. Calculates the watermark position for each image based on alignment and spacing settings.
  5. Returns a slice of images with the watermark applied.

Parameters:

  • inputImg: A slice of input images to which the watermark will be applied.
  • watermarkImg: The watermark image to overlay on each input image.
  • config: SingleConfig struct containing opacity, size, alignment, rotation, and concurrency settings.

Returns:

  • A slice of image.Image objects containing the final images with the watermark applied.
  • An error if any step fails, such as invalid configuration.

Example:

cfg := SingleConfig{
	GeneralConfig: GeneralConfig{
		WatermarkWidthPercent: 20,
		OpacityAlpha:          0.6,
		RotationDegrees:       0,
	},
	VerticalAlign:   VerticalBottom,
	HorizontalAlign: HorizontalRight,
	Spacing:         10,
	MaxWorkers:      4,
}
results, err := BatchApplySingle(inputImages, watermarkImg, cfg)
if err != nil {
	log.Fatal(err)
}

func OpenImage

func OpenImage(path string) (image.Image, error)

OpenImage loads an image from the specified path with auto-orientation support.

The function automatically corrects the image orientation based on EXIF metadata, ensuring that images taken with different device orientations display correctly.

Parameters:

  • path: The file path to the image to be loaded.

Returns:

  • An image.Image containing the loaded image data.
  • An error if the file cannot be read or the format is not supported.

Types

type GeneralConfig

type GeneralConfig struct {
	OpacityAlpha          float64
	WatermarkWidthPercent float64
	RotationDegrees       float64
	ResampleFilter        imaging.ResampleFilter
	MaxWorkers            int
}

GeneralConfig holds common configuration settings for all watermarking operations.

This struct contains the paths to the input image and watermark, along with general appearance settings that apply to any watermarking method (single or grid).

Fields:

  • OpacityAlpha: Transparency level of the watermark (0.0 to 1.0, where 1.0 is fully opaque).
  • WatermarkWidthPercent: Desired watermark width as a percentage of the input image width (0-100).
  • RotationDegrees: Rotation angle for the watermark in degrees (0-360).
  • ResampleFilter: Resampling filter to use when resizing the watermark. (Default is CatmullRom)
  • MaxWorkers: Maximum number of concurrent workers for batch processing (Default is number of CPU cores).

type GridConfig

type GridConfig struct {
	GeneralConfig
	GridSpacingX int
	GridSpacingY int
	OffsetX      int
	OffsetY      int
}

GridConfig holds all configuration settings for applying a grid pattern of watermarks to an image.

This struct extends GeneralConfig with grid-specific options for spacing and positioning. The grid pattern can be controlled using positive values for regular grids, or negative values for overlapping or inverted patterns.

Fields:

  • GeneralConfig: Embedded struct containing common watermarking settings.
  • GridSpacingX: Horizontal spacing between watermarks in the grid (in pixels). Can be negative for overlapping.
  • GridSpacingY: Vertical spacing between watermarks in the grid (in pixels). Can be negative for overlapping.
  • OffsetX: Initial horizontal offset for the grid starting position (in pixels).
  • OffsetY: Initial vertical offset for the grid starting position (in pixels).

type HorizontalAlign

type HorizontalAlign int

HorizontalAlign defines the horizontal alignment options for watermark placement.

Supported values:

  • HorizontalLeft: Aligns the watermark to the left of the image.
  • HorizontalMiddle: Centers the watermark horizontally.
  • HorizontalRight: Aligns the watermark to the right of the image.
  • HorizontalRandom: Places the watermark at a random horizontal position.
const (
	HorizontalLeft HorizontalAlign = iota
	HorizontalMiddle
	HorizontalRight
	HorizontalRandom
)

type SingleConfig

type SingleConfig struct {
	GeneralConfig
	VerticalAlign   VerticalAlign
	HorizontalAlign HorizontalAlign
	Spacing         int
}

SingleConfig holds all configuration settings for applying a single watermark to an image.

This struct extends GeneralConfig with alignment and spacing options specific to single watermark placement.

Fields:

  • GeneralConfig: Embedded struct containing common watermarking settings.
  • VerticalAlign: Vertical alignment of the watermark (top, middle, bottom, or random).
  • HorizontalAlign: Horizontal alignment of the watermark (left, middle, right, or random).
  • Spacing: Distance in pixels between the watermark and the aligned edge.

type VerticalAlign

type VerticalAlign int

VerticalAlign defines the vertical alignment options for watermark placement.

Supported values:

  • VerticalTop: Aligns the watermark to the top of the image.
  • VerticalMiddle: Centers the watermark vertically.
  • VerticalBottom: Aligns the watermark to the bottom of the image.
  • VerticalRandom: Places the watermark at a random vertical position.
const (
	VerticalTop VerticalAlign = iota
	VerticalMiddle
	VerticalBottom
	VerticalRandom
)

Jump to

Keyboard shortcuts

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