imgconv

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package imgconv decides how raster images are stored in a BDF document.

In Keep mode images are stored as they are (decoded pixels become PNG). In Convert mode, images that browsers already decode efficiently (WebP, AVIF, SVG) are kept, and PNG/JPEG/GIF/BMP are re-encoded as WebP when that makes them smaller; otherwise the original bytes are kept. Lossless sources stay lossless unless they look like photographs. The codecs are pure Go (see internal/README.md); building with -tags bdf_noconv leaves them out and Convert behaves like Keep.

Raster inputs whose size on the page is known (a scanned page) are also capped in resolution, in either mode: Options.FitSize says how far to scale one down (at most MaxDPI pixels per inch and MaxPixels pixels) and Resize scales it.

Index

Constants

View Source
const (
	// DefaultMaxDPI is twice the CSS reference pixel density of 96 per inch:
	// a page at its real size on a 2× (Retina) display shows one image pixel
	// per device pixel.
	DefaultMaxDPI = 192
	// DefaultMaxPixels is 3840 × 3840 pixels: the width of a 4K display in
	// both directions (56 MiB decoded as RGBA).
	DefaultMaxPixels = 3840 * 3840
)

The resolution cap of raster inputs (Options.MaxDPI, Options.MaxPixels).

View Source
const MaxDecodePixels = 100 << 20

MaxDecodePixels bounds the images that are decoded, in pixels (width × height). The header of an image states its size and the decoders take the memory for it before they read the pixels, so a file of a hundred bytes could otherwise ask for gigabytes.

Variables

View Source
var ErrNotAvailable = errors.New("imgconv: codecs not compiled in (bdf_noconv)")

ErrNotAvailable is returned in Convert mode when the codecs were left out of the build (-tags bdf_noconv).

View Source
var ErrTooLarge = fmt.Errorf("imgconv: the image has more than %d pixels and is not decoded", MaxDecodePixels)

ErrTooLarge is returned for an image of more than MaxDecodePixels pixels.

Functions

func Available

func Available() bool

Available reports whether the WebP codec is compiled in.

func CSSLength

func CSSLength(s string) (float64, bool)

CSSLength reads an absolute CSS length in CSS px: a number alone is px, and em and ex are those of the default font (16 px). Percentages, lengths that are not positive and what it cannot read are not lengths.

func Decode

func Decode(data []byte) (img image.Image, err error)

Decode decodes PNG, JPEG, GIF, BMP or WebP bytes (AVIF is not decodable here). An image of more than MaxDecodePixels pixels is not decoded: the error is ErrTooLarge.

func EncodeWebP

func EncodeWebP(img *image.NRGBA, quality int, lossless bool) ([]byte, error)

EncodeWebP encodes an image as WebP: lossless, or lossy at a quality from 1 to 100. It returns ErrNotAvailable in builds without the codecs.

func MIME

func MIME(format string) string

MIME returns the media type for a format name.

func Orient

func Orient(img image.Image, o int) image.Image

Orient turns an image as its EXIF orientation says it is displayed.

func Orientation

func Orientation(data []byte) int

Orientation returns the EXIF orientation (1–8) that browsers apply when they draw a JPEG or PNG image (from a JPEG APP1 segment or a PNG eXIf chunk), or 1 when there is none. Browsers draw WebP images as stored.

func PhotoLike

func PhotoLike(img *image.NRGBA, maxColors int) bool

PhotoLike reports whether an image has more than maxColors distinct colours in a sample of its pixels, which makes lossy encoding a reasonable choice.

func Resize

func Resize(img image.Image, w, h int) image.Image

Resize scales img down to w×h pixels by averaging the source pixels each target pixel covers (a box filter, the usual way to downsample scans). The arithmetic is exact integer arithmetic, so the result is the same on every platform.

A two-colour paletted image (a bilevel scan) stays two-colour, which keeps it small: a target pixel takes the less frequent colour (the ink) when that covers at least two fifths of it, a little less than half, so that thin strokes survive without text turning bold. Grey images stay grey; everything else becomes RGBA (premultiplied, so that transparent pixels do not bleed into their neighbours). img is returned as it is when it already has that size or when w or h is not smaller than the source.

func SIMD

func SIMD() bool

SIMD reports whether the codec compiled in runs libwebp's SIMD kernels over simd/archsimd vector registers (a GOEXPERIMENT=simd build on Go 1.27, amd64 or arm64).

func SVGRoot

func SVGRoot(data []byte) (width, height, viewBox string, ok bool)

SVGRoot returns the size attributes of an SVG document's root element; ok is false when the document's first element is not svg.

func Sniff

func Sniff(b []byte) string

Sniff returns the format of encoded image bytes, or "".

Types

type Mode

type Mode int

Mode selects between keeping images and converting them.

const (
	// Keep stores images unchanged; decoded pixel data is written as PNG.
	Keep Mode = iota
	// Convert tries lossless and lossy WebP and keeps the smallest.
	Convert
)

type Options

type Options struct {
	Mode Mode
	// Quality for lossy WebP (and for JPEG, which EncodePixels writes in
	// Keep mode), 1-100 (default 80).
	Quality int
	// Method is the WebP effort, 0 (fast) to 6 (small); default 6.
	Method int
	// NoLossyForLossless keeps lossless sources lossless even when they look like photos.
	NoLossyForLossless bool
	// PhotoColors is the number of distinct sampled colours above which an
	// image counts as a photograph (default 4096).
	PhotoColors int

	// MaxDPI caps the resolution of the raster inputs that are scaled down
	// to fit (see FitSize), in pixels per inch of the page: 0 is
	// DefaultMaxDPI, a negative value removes the cap.
	MaxDPI float64
	// MaxPixels caps the pixel count (width × height) of those inputs: 0 is
	// DefaultMaxPixels, a negative value removes the cap.
	MaxPixels int
}

Options configures conversion.

func (Options) FitSize

func (o Options) FitSize(w, h int, wPt, hPt float64) (int, int)

FitSize returns the size in pixels to store a raster input of w×h pixels that is shown wPt×hPt points large (1/72 inch): each axis is scaled down to at most MaxDPI pixels per inch, then both by the same factor to at most MaxPixels pixels. It never scales up, and an axis whose size on the page is unknown (0) is capped by MaxPixels only.

type Result

type Result struct {
	Data []byte
	// Format is "png", "jpeg", "webp", "avif", "gif", "bmp" or "svg".
	Format string
	// Converted reports whether Data differs from the input.
	Converted bool
	// Lossless reports whether Data reproduces the input pixels exactly.
	Lossless bool
}

Result is a stored image.

func EncodeImage

func EncodeImage(img *image.NRGBA, lossless bool, opts Options) (Result, error)

EncodeImage encodes decoded pixels. lossless says whether they come from a lossless source (so that lossy re-encoding is only used for photographs).

func EncodePixels

func EncodePixels(img image.Image, lossless bool, opts Options) (Result, error)

EncodePixels stores decoded pixels of any image type. lossless says whether they come from a lossless source.

In Keep mode, pixels from a lossless source become PNG in the smallest colour type that holds them (1 bit per pixel for a two-colour image, greyscale, a palette of up to 256 colours), and pixels from a lossy source become JPEG (at Options.Quality) unless they are transparent. In Convert mode, WebP replaces that when it is smaller, as in EncodeImage.

func Optimize

func Optimize(data []byte, opts Options) (Result, error)

Optimize takes encoded image bytes and returns the representation to store.

type SVGSize

type SVGSize struct {
	// W and H are the natural width and height in CSS px (0: none). One that
	// is missing follows from the other and the view box's proportions.
	W, H float64
	// ViewW and ViewH are the width and height of the view box (0: none).
	ViewW, ViewH float64
}

SVGSize is the size an SVG image says it has.

func ParseSVGSize

func ParseSVGSize(width, height, viewBox string) SVGSize

ParseSVGSize reads the width, height and viewBox attributes of an SVG root element. Relative lengths (percentages) are not a natural size.

func (SVGSize) Pixels

func (s SVGSize) Pixels() (w, h float64)

Pixels returns the size of the image's pixels in CSS px (docs/spec.md §6.2): the natural size, else the view box's size, else 300 × 150 (the default size of replaced elements) for what is missing.

func (SVGSize) Ratio

func (s SVGSize) Ratio() float64

Ratio returns the natural aspect ratio (width / height): the view box's, else that of the natural size; 0 when there is none.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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