vips

package module
v0.0.0-...-3fa900b Latest Latest
Warning

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

Go to latest
Published: Jun 20, 2026 License: MIT Imports: 10 Imported by: 0

README

libvips-purego

Minimal, cgo-free Go bindings for libvips, built on purego.

Go Reference Go Report Card

libvips is loaded at runtime via dlopen, so you get fast, low-memory image processing without a C toolchain, CGO_ENABLED=1, or cross-compilation headaches.

Why

  • No cgo — builds with CGO_ENABLED=0; cross-compile freely.
  • Fast & low-memory — libvips streams images and uses a fraction of the memory of most decoders.
  • Tiny surface — a focused API for the common resize / crop / sharpen / encode pipeline.

Requirements

  • Go 1.25+
  • libvips installed on the host (the shared library is loaded at runtime)

Installing libvips

# macOS
brew install vips

# Debian / Ubuntu
apt-get install libvips42

The loader searches standard install locations:

Platform Paths searched
macOS /opt/homebrew/lib (Apple Silicon), /usr/local/lib (Intel)
Linux /usr/lib/x86_64-linux-gnu, /usr/lib/aarch64-linux-gnu, then LD_LIBRARY_PATH

Install

go get github.com/adambenhassen/libvips-purego

Quick start

package main

import (
	"log"
	"os"

	vips "github.com/adambenhassen/libvips-purego"
)

func main() {
	if err := vips.Startup(&vips.Config{MaxCacheSize: 100}); err != nil {
		log.Fatal(err)
	}
	defer vips.Shutdown()

	data, err := os.ReadFile("input.jpg")
	if err != nil {
		log.Fatal(err)
	}

	img, err := vips.NewImageFromBuffer(data)
	if err != nil {
		log.Fatal(err)
	}
	defer img.Close()

	// Resize to 50% and sharpen.
	if err := img.Resize(0.5, vips.KernelLanczos3); err != nil {
		log.Fatal(err)
	}
	if err := img.Sharpen(0.5, 1.5, 2.0); err != nil {
		log.Fatal(err)
	}

	out, _, err := img.ExportWebp(&vips.WebpExportParams{Quality: 80, StripMetadata: true})
	if err != nil {
		log.Fatal(err)
	}

	if err := os.WriteFile("output.webp", out, 0o644); err != nil {
		log.Fatal(err)
	}
}

Usage

Lifecycle

Startup must be called once before any image work, and Shutdown once before exit.

vips.Startup(&vips.Config{
	MaxCacheSize: 100,       // max cached operations (0 disables)
	MaxCacheMem:  50 << 20,  // max cache memory in bytes (0 disables)
})
defer vips.Shutdown()

vips.Version()    // e.g. "8.15.0"
vips.ClearCache() // drop cached operations, keep configured limits

Working with images

img, err := vips.NewImageFromBuffer(data) // JPEG, PNG, WebP, GIF, ...
defer img.Close()                         // idempotent; also run by a finalizer

img.Width()
img.Height()

img.Resize(2.0, vips.KernelLanczos3)      // scale factor + resampling kernel
img.ExtractArea(left, top, w, h)          // crop
img.Sharpen(sigma, x1, m2)                // unsharp mask

Operations mutate the image in place, so they compose naturally in a pipeline.

Encoding

out, _, err := img.ExportWebp(&vips.WebpExportParams{
	Quality:       80,   // 0–100, clamped
	StripMetadata: true,
})

Resampling kernels

Kernel Notes
KernelNearest Fastest, pixelated
KernelLinear Bilinear
KernelCubic Bicubic
KernelMitchell Mitchell–Netravali, good for photos
KernelLanczos2 Lanczos, a=2
KernelLanczos3 Sharpest — recommended default

Concurrency

An Image is not safe for concurrent use. Each goroutine should create and own its own Image, or callers must synchronize access. Startup, Shutdown, and the cache helpers are safe to call from multiple goroutines.

Scope

This is a deliberately small binding covering load → resize / crop / sharpen → WebP. It is not a full libvips wrapper. PRs that extend the operation and codec coverage are welcome.

License

MIT — see LICENSE.

Documentation

Overview

Package vips provides minimal purego bindings for libvips image processing. This package is NOT safe for concurrent use of the same Image instance. Callers must synchronize access if sharing Images across goroutines.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ClearCache

func ClearCache()

ClearCache clears the libvips operation cache. Sets cache to 0, then restores to configured defaults. Does nothing if vips is not initialized.

func Shutdown

func Shutdown()

Shutdown releases all libvips resources. Should be called before program exit.

func Startup

func Startup(config *Config) error

Startup initializes libvips with the given configuration. Must be called before any image operations.

func Version

func Version() string

Version returns the libvips version string (e.g., "8.15.0"). Returns empty string if vips is not initialized or version is unavailable. Call Startup() before calling this function.

Types

type Config

type Config struct {
	MaxCacheSize int // Max operations to cache (0 = disable cache)
	MaxCacheMem  int // Max memory for cache in bytes (0 = disable cache memory limit)
}

Config holds initialization options for libvips.

type Image

type Image struct {
	// contains filtered or unexported fields
}

Image represents a libvips image. Image is NOT safe for concurrent use from multiple goroutines. The caller must synchronize access if sharing an Image across goroutines.

func NewImageFromBuffer

func NewImageFromBuffer(data []byte) (*Image, error)

NewImageFromBuffer loads an image from a byte buffer. Supports JPEG, PNG, WebP, GIF, and other formats that libvips can decode.

func (*Image) Close

func (img *Image) Close()

Close releases the image resources. The image must not be used after calling Close. Close is idempotent and safe to call multiple times.

func (*Image) ExportWebp

func (img *Image) ExportWebp(params *WebpExportParams) ([]byte, *ImageMetadata, error)

ExportWebp exports the image as WebP format. Returns the encoded bytes and the WebP metadata. The second return value is for API compatibility (always nil).

func (*Image) ExtractArea

func (img *Image) ExtractArea(left, top, width, height int) error

ExtractArea extracts a rectangular region from the image. The operation modifies the image in place.

func (*Image) Height

func (img *Image) Height() int

Height returns the image height in pixels. Returns 0 if the image is closed.

func (*Image) IsValid

func (img *Image) IsValid() bool

IsValid returns true if the image has not been closed.

func (*Image) Resize

func (img *Image) Resize(scale float64, kernel Kernel) error

Resize scales the image by the given factor using the specified kernel. A scale of 0.5 halves the size, 2.0 doubles it. The operation modifies the image in place.

func (*Image) Sharpen

func (img *Image) Sharpen(sigma, x1, m2 float64) error

Sharpen applies unsharp masking to the image. Parameters:

  • sigma: gaussian sigma value (typical: 0.5-1.0)
  • x1: flat area threshold (typical: 1.0-2.0)
  • m2: maximum brightening amount (typical: 2.0-4.0)

The operation modifies the image in place.

func (*Image) Width

func (img *Image) Width() int

Width returns the image width in pixels. Returns 0 if the image is closed.

type ImageMetadata

type ImageMetadata struct{}

ImageMetadata is a placeholder for API compatibility. Currently not implemented.

type Kernel

type Kernel int

Kernel defines the resampling kernel for resize operations.

const (
	KernelNearest  Kernel = 0 // Nearest neighbor - fastest, pixelated
	KernelLinear   Kernel = 1 // Bilinear interpolation
	KernelCubic    Kernel = 2 // Bicubic interpolation
	KernelMitchell Kernel = 3 // Mitchell-Netravali - good for photos
	KernelLanczos2 Kernel = 4 // Lanczos with a=2
	KernelLanczos3 Kernel = 5 // Lanczos with a=3 - sharpest, recommended
)

func (Kernel) String

func (k Kernel) String() string

String returns the kernel name for debugging.

type WebpExportParams

type WebpExportParams struct {
	Quality       int  // Quality factor (0-100, default 75). Values outside range are clamped.
	StripMetadata bool // Strip all metadata
}

WebpExportParams configures WebP encoding options.

func NewWebpExportParams

func NewWebpExportParams() *WebpExportParams

NewWebpExportParams returns WebpExportParams with default values.

Directories

Path Synopsis
internal
ffi

Jump to

Keyboard shortcuts

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