Documentation
¶
Overview ¶
Package oneimage is a pure-Go image library: decoding and encoding of image formats, colour management, image operations, and the registry other packages (SVG, text, PSD, metafiles) plug into. It uses only the standard library's image, image/color, image/draw and io types for interop; every codec and the compression underneath it are the library's own.
Two layers ¶
The happy path is a few functions on io.Reader and io.Writer:
img, err := oneimage.Decode(r) // any registered format, upright info, err := oneimage.Identify(r) // size and metadata, no pixels err = oneimage.EncodePNG(w, img, nil) // PNG, APNG for several frames th, err := oneimage.Thumbnail(r, 200, 200) // decode small, scale, strip private metadata err = oneimage.Convert(w, "webp", r, oneimage.ThumbnailOp(200, 200))
A blank import of oneimage/stdreg makes the standard library's image.Decode read every format this package does.
The low layer is the registry: a Format bundles a name, a signature test, a Decoder and an Encoder. Decoders take the whole file as []byte plus a DecodeRequest (limits, region, scale and render-size hints, palette handling) and return an *Image; encoders take an *Image and a format-specific options value. Packages register their formats from init with RegisterFormat, which is how SVG, PSD, metafile and a PDF bridge join without touching the core. A decoder declares which hints it honours itself through Capabilities; the core crops regions for the rest and refuses scaled decoding they cannot do.
Calls that can take long have a Context twin (DecodeContext, OpenContext, EncodeContext, ThumbnailContext, ApplyContext): the context stops them with its error, and is handed to decoders as DecodeRequest.Context. Per-call settings are options: WithLimits and WithParallelism are accepted by every call that takes options, and change nothing else.
The layered-document model (layers, masks, styles, on-demand rendering) is in the subpackage oneimage/layers, SVG in oneimage/svg, rich text in oneimage/text, Photoshop files in oneimage/psd, Windows metafiles in oneimage/metafile and PDF pages in oneimage/pdf (importing it registers the "pdf" format, so Decode reads PDF files too). oneimage/web serves resized images over HTTP and oneimage/stdreg registers the decoders with the standard library's image package.
Opening files ¶
Open reads only the header facts of an image and decodes pixels when they are first asked for, frame by frame (Source.Frame), or a rectangle at a time (Source.Region). Decode, Open and Thumbnail all turn the pixels upright by the Exif orientation (and set it to 1); WithAutoOrient(false) keeps the stored pixels. WithValidate decodes everything up front, and a Registry restricts a call to chosen formats.
Pixels ¶
Pixmap is the concrete raster: a rectangle of interleaved samples in one PixelFormat (colour model, 8-bit, 16-bit, half or 32-bit float samples, alpha none, straight or premultiplied). It implements image.Image and [draw.Image]. FromImage turns any image.Image into a Pixmap, sharing the samples of the common standard-library types, and Pixmap.Convert changes format. An Image holds frames (each a full-canvas picture with a delay), a loop count, Metadata (ICC profile, Exif, XMP and text blobs, carried through decode and encode) and the source format's own facts in Details.
Alpha follows the standard library's names. Pixel formats called NRGBA (NRGBA8, NRGBA16, NRGBAF32) hold straight (non-premultiplied) colour, like image.NRGBA; formats called RGBA (RGBA8, RGBA16, RGBAF32) hold premultiplied colour, like image.RGBA. Gray with alpha has one straight form per depth (GrayAlpha8, GrayAlpha16).
Geometry ¶
Pixel coordinates have the origin at the top-left corner of the top-left pixel, x to the right and y down (a pixel centre is at +0.5), so positive angles turn clockwise on screen. Vec2 is the one float point type. The one affine map is Matrix3x2, written in SVG's order matrix(a b c d e f), applied to a point as x' = a*x + c*y + e, y' = b*x + d*y + f; build it with TranslationMatrix, ScaleMatrix, RotationMatrix and SkewMatrix, chain it with Matrix3x2.Mul, Matrix3x2.Rotate and friends (each step happens after the ones before it) and move its fixed point with Matrix3x2.Around. Affine applies one to an image. The 3x3 Matrix is for perspective only (Perspective, MatrixBuilder) and converts to and from Matrix3x2.
Operations ¶
An Op is an immutable value with a language-neutral name and parameters that applies to every frame of an Image: Resize, Crop, Pad, Rotate, Flip, AutoOrient, Affine, Perspective and the others. Apply runs a chain, Describe lists its graph, and an operation whose parameters change nothing returns its input itself. Thumbnail is the happy path: decode (at reduced size where the format allows), turn upright, scale, keep only the colour profile; ThumbnailOp carries the same rule into a chain, and Convert runs decode, ops and encode in one call.
Resampling is separable float32 on premultiplied alpha, in linear light unless WithLinear(false), with pixel-centre mapping and replicated edges; results do not depend on how many goroutines did the work.
Colour management ¶
ParseProfile reads ICC v2 and v4 profiles (matrix/TRC, gray, and lut8, lut16, lutAToB and lutBToA tables for RGB, CMYK and Lab) and the built-ins (SRGB, DisplayP3, GenericCMYK, ...) need no files. Pixmap.ConvertColor and Image.ConvertColor convert between profiles under any of the four RenderingIntent values, with black point compensation on by default; NewColorTransform is the reusable low-level form, cached in a byte-bounded cache. ToSRGB is the happy path. Eight- and sixteen-bit images of 262,144 pixels or more convert table-based profiles through a precomputed grid, smaller ones and all float data use the exact arithmetic. CMYK and Lab pixmaps convert to other pixel formats (Pixmap.Convert) through the default profiles.
Options ¶
Four idioms are used, each where it fits. A format with many independent settings takes a struct whose zero value is the default (PNGOptions, JPEGOptions, WebPOptions); a field whose zero would be a real value says so in its first sentence (a sentinel such as PNGNoCompression). Calls that vary per use take functional options: DecodeOption, EncodeOption, OpOption and ColorOption are sealed interfaces, so WithLimits and WithParallelism are one function each, accepted by all of them, while an option an operation does not read is ignored (Describe reports it). Things built up in steps use a builder (PathBuilder, MatrixBuilder). Entities that change over time have setters ([layers.Document] layers). The same names mean the same everywhere: WithLimits bounds a call's resources, WithParallelism its goroutines (both default to the settings of the registry or SetParallelism), and Limits fields follow one rule, zero for the default and negative for off.
Streaming writers ¶
NewPNGWriter, NewJPEGWriter, NewTIFFWriter and NewBMPWriter take the destination, the size and a PixelFormat, then rows or bands from the top of the image down. WriteBands does not close the writer; Close finishes the file, can be called again (it returns its first result) and never closes the destination. None of them is safe for concurrent use. The TIFF writer needs an io.WriteSeeker because the format puts the first directory's offset in the header. So does the BMP writer for the default bottom-up file, which stores the last row first; with BMPOptions.TopDown any io.Writer will do.
Errors and limits ¶
Failures fall in the categories ErrFormat (damaged or unrecognised data), ErrLimit (a resource bound), ErrUnsupported (valid but not handled) and ErrOperation (an impossible request), matched with errors.Is; the typed errors FormatError, LimitError and UnsupportedError carry details. Limits bound dimensions, pixels, frames, metadata and expansion, and are checked against headers before memory is allocated. All input is treated as hostile.
Determinism ¶
The same bytes and options always give the same pixels and, for encoders, the same output bytes. Lossless decoders are bit-exact.
Example (Readme) ¶
The README's opening program, run on a 1200 x 900 photograph and a Letter page in a scratch directory.
package main
import (
"bytes"
"fmt"
"image"
"image/color"
"log"
"os"
"recursiveai.org/go/oneimage"
"recursiveai.org/go/oneimage/pdf"
)
// readmeMain is the program the README opens with, line for line (a test
// compares them): a JPEG becomes a WebP thumbnail and page 1 of a PDF becomes
// a PNG.
func readmeMain() {
photo, err := os.Open("photo.jpg")
if err != nil {
log.Fatal(err)
}
defer photo.Close()
thumb, err := oneimage.Thumbnail(photo, 400, 400)
if err != nil {
log.Fatal(err)
}
out, err := os.Create("thumb.webp")
if err != nil {
log.Fatal(err)
}
defer out.Close()
if err := oneimage.EncodeWebP(out, thumb, &oneimage.WebPOptions{Quality: 80}); err != nil {
log.Fatal(err)
}
report, err := os.Open("report.pdf")
if err != nil {
log.Fatal(err)
}
defer report.Close()
page, err := pdf.RenderPage(report, 0, pdf.WithDPI(150))
if err != nil {
log.Fatal(err)
}
png, err := os.Create("page1.png")
if err != nil {
log.Fatal(err)
}
defer png.Close()
if err := oneimage.EncodePNG(png, page, nil); err != nil {
log.Fatal(err)
}
}
const readmePDF = "%PDF-1.4\n" +
"1 0 obj\n<< /Length 30 >>\nstream\n1 0 0 rg 0 0 8 8 re f 0 0 1 rg 8 0 4 4 re f\nendstream\nendobj\n" +
"2 0 obj\n<< /Type /Page /Parent 3 0 R /MediaBox [0 0 612 792] /Contents 1 0 R >>\nendobj\n" +
"3 0 obj\n<< /Type /Pages /Kids [2 0 R] /Count 1 >>\nendobj\n" +
"4 0 obj\n<< /Type /Catalog /Pages 3 0 R >>\nendobj\n" +
"trailer\n<< /Size 5 /Root 4 0 R >>\n%%EOF\n"
func main() {
dir, err := os.MkdirTemp("", "readme")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
wd, _ := os.Getwd()
if err := os.Chdir(dir); err != nil {
log.Fatal(err)
}
defer os.Chdir(wd)
src := image.NewNRGBA(image.Rect(0, 0, 1200, 900))
for y := 0; y < 900; y++ {
for x := 0; x < 1200; x++ {
src.SetNRGBA(x, y, color.NRGBA{uint8(x / 5), uint8(y / 4), uint8(x + y), 255})
}
}
var jpg bytes.Buffer
if err := oneimage.EncodeJPEG(&jpg, src, nil); err != nil {
log.Fatal(err)
}
os.WriteFile("photo.jpg", jpg.Bytes(), 0o644)
os.WriteFile("report.pdf", []byte(readmePDF), 0o644)
readmeMain()
for _, name := range []string{"thumb.webp", "page1.png"} {
f, err := os.Open(name)
if err != nil {
log.Fatal(err)
}
info, err := oneimage.Identify(f)
f.Close()
if err != nil {
log.Fatal(err)
}
fmt.Println(name, info.Format, info.Width, info.Height)
}
}
Output: thumb.webp webp 400 300 page1.png png 1275 1650
Index ¶
- Constants
- Variables
- func BlendRow(dst, src []float32, mode BlendMode, comp AlphaComposition, opacity float32)
- func BuiltinNames() []string
- func Convert(w io.Writer, format string, r io.Reader, ops ...Op) error
- func ConvertContext(ctx context.Context, w io.Writer, format string, r io.Reader, ops ...Op) error
- func Describe(img *Image, ops ...Op) ([]string, error)
- func Encode(w io.Writer, img image.Image, format string, opts any, eopts ...EncodeOption) error
- func EncodeBMP(w io.Writer, img image.Image, opts *BMPOptions) error
- func EncodeBytes(img image.Image, format string, opts any, eopts ...EncodeOption) ([]byte, error)
- func EncodeBytesContext(ctx context.Context, img image.Image, format string, opts any, ...) ([]byte, error)
- func EncodeContext(ctx context.Context, w io.Writer, img image.Image, format string, opts any, ...) error
- func EncodeGIF(w io.Writer, img image.Image, opts *GIFOptions) error
- func EncodeICO(w io.Writer, img image.Image, opts *ICOOptions) error
- func EncodeJPEG(w io.Writer, img image.Image, opts *JPEGOptions) error
- func EncodePNG(w io.Writer, img image.Image, opts *PNGOptions) error
- func EncodeTIFF(w io.Writer, img image.Image, opts *TIFFOptions) error
- func EncodeWebP(w io.Writer, img image.Image, opts *WebPOptions) error
- func ExifForOutput(exif []byte, width, height, orientation int) ([]byte, error)
- func ExifOrientation(exif []byte) int
- func FitRenderSize(natW, natH float64, reqW, reqH int) (w, h int, err error)
- func FormatNames() []string
- func FormatOp(op Op) string
- func Parallelism() int
- func RegisterFormat(f Format)
- func ResizePixmap(dst *Pixmap, src image.Image, opts ...OpOption) error
- func ResizeSize(sw, sh, width, height int, fit Fit, upscale bool) (w, h int, err error)
- func SetColorCacheBudget(bytes int64)
- func SetParallelism(n int)
- func WebSafePalette() []color.NRGBA
- func WernerPalette() []color.NRGBA
- type AlphaComposition
- type AlphaMode
- type AnalysisOption
- type Anchor
- type Axis
- type BMPInfo
- type BMPOptions
- type BMPWriter
- type BackdropBrush
- type BlendMode
- type BlindnessMode
- type BooleanOp
- type BrightnessMode
- type Brush
- func EllipticGradientBrush(centre, axisEnd Vec2, axisRatio float64, stops []Stop, opts ...BrushOption) (Brush, error)
- func HatchBrush(style HatchStyle, foreground, background color.NRGBA, opts ...BrushOption) (Brush, error)
- func ImageBrush(src image.Image, opts ...BrushOption) (Brush, error)
- func LinearGradientBrush(start, end Vec2, stops []Stop, opts ...BrushOption) (Brush, error)
- func PathGradientBrush(points []Vec2, colors []color.NRGBA, opts ...BrushOption) (Brush, error)
- func PatternBrush(cells [][]bool, foreground, background color.NRGBA, opts ...BrushOption) (Brush, error)
- func RadialGradientBrush(centre Vec2, radius float64, stops []Stop, opts ...BrushOption) (Brush, error)
- func RecolorBrush(source, target color.NRGBA, threshold float64) (Brush, error)
- func SolidBrush(c color.NRGBA) Brush
- type BrushOption
- func WithBrushTransform(m Matrix3x2) BrushOption
- func WithFocal(focal Vec2, focalRadius float64) BrushOption
- func WithPathGradientCentre(p Vec2, c color.NRGBA) BrushOption
- func WithRepetition(r Repetition) BrushOption
- func WithSampling(s Sampling) BrushOption
- func WithSourceOffset(dx, dy float64) BrushOption
- func WithSourceRegion(r image.Rectangle) BrushOption
- func WithSquaredDistance() BrushOption
- func WithStraightBlend() BrushOption
- func WithoutTiling() BrushOption
- type Capabilities
- type Channel
- type ChannelStats
- type ColorMatrix
- type ColorModel
- type ColorOption
- type ColorTransform
- type CommonOption
- type CurveInterpolation
- type DecodeOption
- func WithAutoOrient(v bool) DecodeOption
- func WithFormat(name string) DecodeOption
- func WithFrameLimit(n int) DecodeOption
- func WithKeepIndexed() DecodeOption
- func WithRegion(r image.Rectangle) DecodeOption
- func WithRegistry(r *Registry) DecodeOption
- func WithRenderSize(w, h int) DecodeOption
- func WithScale(n int) DecodeOption
- func WithSourceCheck(check func() error) DecodeOption
- func WithValidate(v bool) DecodeOption
- type DecodeRequest
- type Decoder
- type Dither
- type DrawOption
- func WithClipPath(clip Path, rule FillRule) DrawOption
- func WithDrawBlend(m BlendMode) DrawOption
- func WithDrawComposition(c AlphaComposition) DrawOption
- func WithDrawOpacity(v float64) DrawOption
- func WithFillRule(r FillRule) DrawOption
- func WithFlatness(tolerance float64) DrawOption
- func WithLinearLight() DrawOption
- func WithTransform(m Matrix3x2) DrawOption
- func WithoutAntialiasing() DrawOption
- type Edge
- type EdgeDetector
- type EncodeOption
- type EncodeRequest
- type Encoder
- type EncoderInfo
- type EqualizeMethod
- type ExifFields
- type FillRule
- type Filter
- type Fit
- type Format
- type FormatError
- type Frame
- type FrameInfo
- type GIFDisposal
- type GIFFrameInfo
- type GIFInfo
- type GIFOptions
- type GPS
- type HatchStyle
- type Histogram
- type ICOEntry
- type ICOInfo
- type ICOOptions
- type Image
- func Apply(img *Image, ops ...Op) (*Image, error)
- func ApplyContext(ctx context.Context, img *Image, ops ...Op) (*Image, error)
- func CombineChannels(channels ...*Image) (*Image, error)
- func Decode(r io.Reader, opts ...DecodeOption) (*Image, error)
- func DecodeBytes(data []byte, opts ...DecodeOption) (*Image, error)
- func DecodeBytesContext(ctx context.Context, data []byte, opts ...DecodeOption) (*Image, error)
- func DecodeContext(ctx context.Context, r io.Reader, opts ...DecodeOption) (*Image, error)
- func NewAnimation(loopCount int, frames ...Frame) (*Image, error)
- func NewImage(img image.Image) *Image
- func SplitChannels(img *Image) ([]*Image, error)
- func Thumbnail(r io.Reader, width, height int, opts ...OpOption) (*Image, error)
- func ThumbnailBytes(data []byte, width, height int, opts ...OpOption) (*Image, error)
- func ThumbnailBytesContext(ctx context.Context, data []byte, width, height int, opts ...OpOption) (*Image, error)
- func ThumbnailContext(ctx context.Context, r io.Reader, width, height int, opts ...OpOption) (*Image, error)
- func ThumbnailImage(img image.Image, width, height int, opts ...OpOption) (*Image, error)
- func ThumbnailImageContext(ctx context.Context, img image.Image, width, height int, opts ...OpOption) (*Image, error)
- func ToSRGB(m *Image) (*Image, error)
- func (m *Image) All() iter.Seq2[int, Frame]
- func (m *Image) Animated() bool
- func (m *Image) Apply(ops ...Op) (*Image, error)
- func (m *Image) ApplyContext(ctx context.Context, ops ...Op) (*Image, error)
- func (m *Image) AssignProfile(p *Profile) *Image
- func (m *Image) At(x, y int) color.Color
- func (m *Image) Bounds() image.Rectangle
- func (m *Image) ClearColor(c color.NRGBA) (*Image, error)
- func (m *Image) ClipPath(path Path, fn func(*Pixmap) (*Pixmap, error), opts ...DrawOption) (*Image, error)
- func (m *Image) ColorModel() color.Model
- func (m *Image) ConvertColor(src, dst *Profile, opts ...ColorOption) (*Image, error)
- func (m *Image) ConvertColorContext(ctx context.Context, src, dst *Profile, opts ...ColorOption) (*Image, error)
- func (m *Image) ConvertPixels(f PixelFormat) (*Image, error)
- func (m *Image) Duration() time.Duration
- func (m *Image) Edit(fn func(frame *Pixmap) error) (*Image, error)
- func (m *Image) FillColor(c color.NRGBA, opts ...DrawOption) (*Image, error)
- func (m *Image) FillPath(brush Brush, path Path, opts ...DrawOption) (*Image, error)
- func (m *Image) Frame(i int) (*Image, error)
- func (m *Image) Height() int
- func (m *Image) Histogram(bins int, opts ...AnalysisOption) (*Histogram, error)
- func (m *Image) Profile() (*Profile, bool)
- func (m *Image) Statistics(opts ...AnalysisOption) (*Statistics, error)
- func (m *Image) StripMetadata(keepICC bool) *Image
- func (m *Image) StrokePath(pen Pen, path Path, opts ...DrawOption) (*Image, error)
- func (m *Image) Width() int
- func (m *Image) WithDelays(delays ...time.Duration) (*Image, error)
- func (m *Image) WithFrames(frames ...Frame) (*Image, error)
- func (m *Image) WithLoopCount(n int) (*Image, error)
- type Info
- type InfoEncoder
- type JPEGComponent
- type JPEGInfo
- type JPEGJFIF
- type JPEGOptions
- type JPEGSubsampling
- type JPEGWriter
- type LimitError
- type Limits
- func (l Limits) CheckFrame(format string, width, height int) error
- func (l Limits) CheckFrameBytes(format string, width, height, bytesPerPixel int) error
- func (l Limits) CheckFrames(format string, sizes []image.Point) error
- func (l Limits) CheckMetadata(format string, m Metadata) error
- func (l Limits) CheckMetadataBytes(format string, n int64) error
- func (l Limits) CheckTotal(format string, frames, width, height int) error
- func (l Limits) Resolved() Limits
- type Matrix
- type Matrix3x2
- func (m Matrix3x2) Apply(p Vec2) Vec2
- func (m Matrix3x2) Around(ox, oy float64) Matrix3x2
- func (m Matrix3x2) Invert() (Matrix3x2, bool)
- func (m Matrix3x2) Matrix() Matrix
- func (m Matrix3x2) Mul(n Matrix3x2) Matrix3x2
- func (m Matrix3x2) Rotate(degrees float64) Matrix3x2
- func (m Matrix3x2) Scale(sx, sy float64) Matrix3x2
- func (m Matrix3x2) Skew(dxDegrees, dyDegrees float64) Matrix3x2
- func (m Matrix3x2) Translate(dx, dy float64) Matrix3x2
- type MatrixBuilder
- func (b *MatrixBuilder) AppendMatrix(m Matrix) *MatrixBuilder
- func (b *MatrixBuilder) AppendQuad(corners [4]Vec2) *MatrixBuilder
- func (b *MatrixBuilder) AppendRotationAbout(degrees, cx, cy float64) *MatrixBuilder
- func (b *MatrixBuilder) AppendRotationDegrees(degrees float64) *MatrixBuilder
- func (b *MatrixBuilder) AppendScale(x, y float64) *MatrixBuilder
- func (b *MatrixBuilder) AppendSkewAbout(x, y, ox, oy float64) *MatrixBuilder
- func (b *MatrixBuilder) AppendSkewDegrees(x, y float64) *MatrixBuilder
- func (b *MatrixBuilder) AppendTaper(side TaperSide, corner TaperCorner, amount float64) *MatrixBuilder
- func (b *MatrixBuilder) AppendTranslation(x, y float64) *MatrixBuilder
- func (b *MatrixBuilder) Matrix(width, height int) (Matrix, error)
- func (b *MatrixBuilder) PrependMatrix(m Matrix) *MatrixBuilder
- func (b *MatrixBuilder) PrependQuad(corners [4]Vec2) *MatrixBuilder
- func (b *MatrixBuilder) PrependRotationAbout(degrees, cx, cy float64) *MatrixBuilder
- func (b *MatrixBuilder) PrependRotationDegrees(degrees float64) *MatrixBuilder
- func (b *MatrixBuilder) PrependScale(x, y float64) *MatrixBuilder
- func (b *MatrixBuilder) PrependSkewAbout(x, y, ox, oy float64) *MatrixBuilder
- func (b *MatrixBuilder) PrependSkewDegrees(x, y float64) *MatrixBuilder
- func (b *MatrixBuilder) PrependTaper(side TaperSide, corner TaperCorner, amount float64) *MatrixBuilder
- func (b *MatrixBuilder) PrependTranslation(x, y float64) *MatrixBuilder
- type Metadata
- func (m Metadata) ColorProfile() (p *Profile, ok bool)
- func (m Metadata) EffectiveOrientation() int
- func (m Metadata) ReadExif() (ExifFields, error)
- func (m Metadata) Stripped(keepICC bool) Metadata
- func (m Metadata) TotalBytes() int
- func (m Metadata) WithICC(icc []byte) Metadata
- func (m Metadata) WithOrientation(o int) (Metadata, error)
- type Op
- func AdaptiveThreshold(limit float64, opts ...OpOption) Op
- func AddAlpha(alpha float64) Op
- func Affine(m Matrix3x2, opts ...OpOption) Op
- func ApplyColorMatrix(m ColorMatrix) Op
- func ApplyMask(mask *Image, x, y int, opts ...OpOption) Op
- func AutoLevel(opts ...OpOption) Op
- func AutoOrient() Op
- func BinaryDither(d Dither, opts ...OpOption) Op
- func BlackWhite() Op
- func BokehBlur(radius, components int, gamma float64, opts ...OpOption) Op
- func BoxBlur(radius int, opts ...OpOption) Op
- func BrightnessContrast(brightness, contrast float64, opts ...OpOption) Op
- func ChannelMixer(matrix []float64, opts ...OpOption) Op
- func Clear(c color.Color) Op
- func ColorBlindness(mode BlindnessMode) Op
- func Composite(overlay *Image, x, y int, opts ...OpOption) Op
- func Convolve(kernel [][]float64, divisor, offset float64, opts ...OpOption) Op
- func Crop(r image.Rectangle) Op
- func Curves(points []Vec2, opts ...OpOption) Op
- func DetectEdges(detector EdgeDetector, grayscale bool, opts ...OpOption) Op
- func DitherToPalette(palette []color.Color, d Dither, opts ...OpOption) Op
- func EntropyCrop(threshold float64) Op
- func Exposure(stops float64, opts ...OpOption) Op
- func Fill(c color.Color, opts ...OpOption) Op
- func Flatten(opts ...OpOption) Op
- func Flip(axis Axis) Op
- func Gamma(gamma float64, opts ...OpOption) Op
- func GaussianBlur(sigma float64, opts ...OpOption) Op
- func GaussianSharpen(sigma float64, opts ...OpOption) Op
- func Glow(c color.Color, radius float64, opts ...OpOption) Op
- func Grayscale(opts ...OpOption) Op
- func HistogramEqualization(opts ...OpOption) Op
- func HueSaturationLightness(hue, saturation, lightness float64, opts ...OpOption) Op
- func Invert(opts ...OpOption) Op
- func Kodachrome() Op
- func Levels(inBlack, inWhite, gamma, outBlack, outWhite float64, opts ...OpOption) Op
- func Lomograph() Op
- func Median(radius int, opts ...OpOption) Op
- func OilPaint(levels, brushSize int) Op
- func Opacity(amount float64) Op
- func Pad(left, top, right, bottom int, opts ...OpOption) Op
- func Perspective(m Matrix, opts ...OpOption) Op
- func PerspectiveBuilder(b *MatrixBuilder, opts ...OpOption) Op
- func PerspectiveCorners(corners [4]Vec2, opts ...OpOption) Op
- func Pixelate(size int) Op
- func Polaroid() Op
- func Posterize(levels int, opts ...OpOption) Op
- func Quantize(colors int, opts ...OpOption) Op
- func RemoveAlpha() Op
- func Reorient(o int) Op
- func Resize(width, height int, opts ...OpOption) Op
- func ResizeInto(canvasWidth, canvasHeight, x, y, width, height int, opts ...OpOption) Op
- func Rotate(degrees float64, opts ...OpOption) Op
- func Sepia(amount float64) Op
- func Sharpen(amount, radius, threshold float64, opts ...OpOption) Op
- func Sobel(scale float64, opts ...OpOption) Op
- func Threshold(level float64, opts ...OpOption) Op
- func ThumbnailOp(width, height int, opts ...OpOption) Op
- func Trim(threshold int, opts ...OpOption) Op
- func Vignette(c color.Color, radiusX, radiusY float64, opts ...OpOption) Op
- type OpOption
- func WithAnchor(a Anchor) OpOption
- func WithArea(r image.Rectangle) OpOption
- func WithBackground(c color.Color) OpOption
- func WithBlend(m BlendMode) OpOption
- func WithBrightnessMode(m BrightnessMode) OpOption
- func WithChannel(c Channel) OpOption
- func WithClipLimit(limit float64) OpOption
- func WithColors(upper, lower color.Color) OpOption
- func WithComposition(a AlphaComposition) OpOption
- func WithCurveInterpolation(i CurveInterpolation) OpOption
- func WithDither(d Dither) OpOption
- func WithDitherScale(s float64) OpOption
- func WithEdge(e Edge) OpOption
- func WithEqualization(levels, tiles int) OpOption
- func WithEqualizeMethod(m EqualizeMethod) OpOption
- func WithExpand(on bool) OpOption
- func WithFilter(f Filter) OpOption
- func WithFit(f Fit) OpOption
- func WithGrayFormat(on bool) OpOption
- func WithKeepMetadata(on bool) OpOption
- func WithLinear(on bool) OpOption
- func WithMaskLuminance(on bool) OpOption
- func WithOpacity(a float64) OpOption
- func WithPerChannel(on bool) OpOption
- func WithPosterizeMode(m PosterizeMode) OpOption
- func WithQuantizeAlpha(a QuantizeAlpha) OpOption
- func WithQuantizer(q Quantizer) OpOption
- func WithSigmaY(s float64) OpOption
- func WithSyncChannels(on bool) OpOption
- func WithUpscale(on bool) OpOption
- type PNGColor
- type PNGFilter
- type PNGInfo
- type PNGOptions
- type PNGWriter
- type Param
- type Path
- func CirclePath(cx, cy, r float64) (Path, error)
- func CombinePaths(paths ...Path) (Path, error)
- func EllipsePath(cx, cy, rx, ry float64) (Path, error)
- func ParsePath(svg string) (Path, error)
- func PolygonPath(points []Vec2) (Path, error)
- func PolylinePath(points []Vec2) (Path, error)
- func RectPath(x, y, w, h float64) (Path, error)
- func RegularPolygonPath(cx, cy float64, sides int, r, rotationDegrees float64) (Path, error)
- func RoundedRectPath(x, y, w, h, r float64) (Path, error)
- func StarPath(cx, cy float64, prongs int, innerRadius, outerRadius, rotationDegrees float64) (Path, error)
- func UnionAll(paths []Path, opts ...PathOption) (Path, error)
- func (p Path) Boolean(op BooleanOp, other Path, opts ...PathOption) (Path, error)
- func (p Path) Bounds() (PathBounds, bool)
- func (p Path) CurrentPoint() (Vec2, bool)
- func (p Path) FigureCount() int
- func (p Path) Flatten(tolerance float64) ([]Polyline, error)
- func (p Path) Intersect(other Path, opts ...PathOption) (Path, error)
- func (p Path) IsEmpty() bool
- func (p Path) Length(tolerance float64) (float64, error)
- func (p Path) Offset(distance float64, join StrokeJoin, opts ...PathOption) (Path, error)
- func (p Path) Outline(pen Pen, tolerance float64) (Path, error)
- func (p Path) Resolve(rule FillRule, opts ...PathOption) (Path, error)
- func (p Path) Reverse() Path
- func (p Path) Rotate(degrees, cx, cy float64) Path
- func (p Path) SVG() string
- func (p Path) Scale(sx, sy float64) Path
- func (p Path) Subtract(other Path, opts ...PathOption) (Path, error)
- func (p Path) Transform(m Matrix3x2) Path
- func (p Path) Translate(dx, dy float64) Path
- func (p Path) Union(other Path, opts ...PathOption) (Path, error)
- func (p Path) Xor(other Path, opts ...PathOption) (Path, error)
- type PathBounds
- type PathBuilder
- func (b *PathBuilder) AddPath(p Path) *PathBuilder
- func (b *PathBuilder) ArcTo(rx, ry, rotationDegrees float64, large, sweep bool, x, y float64) *PathBuilder
- func (b *PathBuilder) Close() *PathBuilder
- func (b *PathBuilder) CubicTo(c1x, c1y, c2x, c2y, x, y float64) *PathBuilder
- func (b *PathBuilder) CurrentPoint() Vec2
- func (b *PathBuilder) LineTo(x, y float64) *PathBuilder
- func (b *PathBuilder) MoveTo(x, y float64) *PathBuilder
- func (b *PathBuilder) Path() (Path, error)
- func (b *PathBuilder) QuadTo(cx, cy, x, y float64) *PathBuilder
- func (b *PathBuilder) Reset() *PathBuilder
- type PathOption
- type Pen
- type PixelFormat
- func (f PixelFormat) BitDepth() int
- func (f PixelFormat) BytesPerPixel() int
- func (f PixelFormat) BytesPerSample() int
- func (f PixelFormat) Channels() int
- func (f PixelFormat) ColorChannels() int
- func (f PixelFormat) HasAlpha() bool
- func (f PixelFormat) String() string
- func (f PixelFormat) Valid() bool
- type Pixmap
- func (p *Pixmap) At(x, y int) color.Color
- func (p *Pixmap) Bounds() image.Rectangle
- func (p *Pixmap) ClearColor(c color.NRGBA) error
- func (p *Pixmap) ClipPath(path Path, fn func(*Pixmap) (*Pixmap, error), opts ...DrawOption) error
- func (p *Pixmap) Clone() *Pixmap
- func (p *Pixmap) CloneRegion(r image.Rectangle) (*Pixmap, error)
- func (p *Pixmap) ColorModel() color.Model
- func (p *Pixmap) Convert(f PixelFormat) (*Pixmap, error)
- func (p *Pixmap) ConvertColor(src, dst *Profile, opts ...ColorOption) (*Pixmap, error)
- func (p *Pixmap) CopyFromImage(src image.Image, x, y int) error
- func (p *Pixmap) CopyRegion(dst []byte, stride int, r image.Rectangle) error
- func (p *Pixmap) DrawBeziers(pen Pen, points []Vec2, opts ...DrawOption) error
- func (p *Pixmap) DrawEllipse(pen Pen, cx, cy, rx, ry float64, opts ...DrawOption) error
- func (p *Pixmap) DrawLine(pen Pen, from, to Vec2, opts ...DrawOption) error
- func (p *Pixmap) DrawPolygon(pen Pen, points []Vec2, opts ...DrawOption) error
- func (p *Pixmap) DrawPolyline(pen Pen, points []Vec2, opts ...DrawOption) error
- func (p *Pixmap) DrawRect(pen Pen, x, y, w, h float64, opts ...DrawOption) error
- func (p *Pixmap) FillColor(c color.NRGBA, opts ...DrawOption) error
- func (p *Pixmap) FillPath(brush Brush, path Path, opts ...DrawOption) error
- func (p *Pixmap) Opaque() bool
- func (p *Pixmap) PackedRowBytes(width int) int
- func (p *Pixmap) Row8(y int) []uint8
- func (p *Pixmap) Row16(y int) []uint16
- func (p *Pixmap) RowF(y int) []float32
- func (p *Pixmap) Set(x, y int, c color.Color)
- func (p *Pixmap) SetRegion(src []byte, stride int, r image.Rectangle) error
- func (p *Pixmap) StdImage() image.Image
- func (p *Pixmap) StrideBytes() int
- func (p *Pixmap) StrokePath(pen Pen, path Path, opts ...DrawOption) error
- func (p *Pixmap) SubImage(r image.Rectangle) image.Image
- type Polyline
- type PosterizeMode
- type Profile
- func BuiltinProfile(name string) (*Profile, bool)
- func DefaultProfile(m ColorModel) *Profile
- func DisplayP3() *Profile
- func GenericCMYK() *Profile
- func GrayProfile() *Profile
- func LabD50() *Profile
- func ParseProfile(data []byte) (*Profile, error)
- func ParseProfileLimits(data []byte, lim Limits) (*Profile, error)
- func ProPhoto() *Profile
- func Rec2020() *Profile
- func SRGB() *Profile
- func SRGBCompact() *Profile
- func WideGamutRGB() *Profile
- type QuantizeAlpha
- type Quantizer
- type ReaderAtDecoder
- type Registry
- func (r *Registry) Add(f Format) error
- func (r *Registry) Detect(head []byte) (Format, bool)
- func (r *Registry) ForExtension(ext string) (Format, bool)
- func (r *Registry) Formats() []Format
- func (r *Registry) Limits() Limits
- func (r *Registry) Lookup(name string) (Format, bool)
- func (r *Registry) Names() []string
- func (r *Registry) SetLimits(l Limits)
- type RenderingIntent
- type Repetition
- type RowDecoder
- type SampleType
- type Sampling
- type SolidColorBrush
- type Source
- func Open(data []byte, opts ...DecodeOption) (*Source, error)
- func OpenContext(ctx context.Context, data []byte, opts ...DecodeOption) (*Source, error)
- func OpenReader(r io.Reader, opts ...DecodeOption) (*Source, error)
- func OpenReaderAt(r io.ReaderAt, size int64, opts ...DecodeOption) (*Source, error)
- func OpenReaderAtContext(ctx context.Context, r io.ReaderAt, size int64, opts ...DecodeOption) (*Source, error)
- func OpenReaderContext(ctx context.Context, r io.Reader, opts ...DecodeOption) (*Source, error)
- func (s *Source) Bands(i int, r image.Rectangle, rows int) iter.Seq2[*Pixmap, error]
- func (s *Source) Bounds() image.Rectangle
- func (s *Source) Frame(i int) (Frame, error)
- func (s *Source) Image() (*Image, error)
- func (s *Source) Info() Info
- func (s *Source) Metadata() Metadata
- func (s *Source) NumFrames() int
- func (s *Source) Region(i int, r image.Rectangle) (*Pixmap, error)
- func (s *Source) Release()
- func (s *Source) Thumbnail(width, height int, opts ...OpOption) (*Image, error)
- type SourceChangedError
- type Statistics
- type Stop
- type StrokeCap
- type StrokeJoin
- type TIFFCompression
- type TIFFInfo
- type TIFFOptions
- type TIFFPage
- type TIFFWriter
- type TaperCorner
- type TaperSide
- type TextEntry
- type UnsupportedError
- type Vec2
- type WebPExact
- type WebPInfo
- type WebPOptions
Examples ¶
- Package (Readme)
- Apply
- ApplyContext
- ApplyMask
- BMPWriter
- BestFormat
- BlendRow
- BrightnessContrast
- ColorMatrix.Then
- Composite
- Convert
- Curves
- Decode
- DecodeContext
- Describe
- Describe (IgnoredOptions)
- DetectEdges
- DitherToPalette
- EncodeBMP
- EncodeGIF
- EncodeICO
- EncodeJPEG
- EncodePNG (Indexed)
- EncodeTIFF
- EncodeWebP
- ExifForOutput
- Fill
- Frame.Pixmap
- GIFOptions
- Gamma
- GaussianBlur
- Grayscale
- HatchBrush
- HistogramEqualization
- Identify
- Image.ConvertColor
- Image.Edit
- Image.Frame
- Image.Statistics
- JPEGWriter
- Levels
- LinearGradientBrush
- LookupFormat
- Matrix3x2.Around
- Matrix3x2.Matrix
- MatrixBuilder
- Median
- Metadata.ReadExif
- Metadata.Stripped
- NewAnimation
- NewPNGWriter
- NewPixmapFromBytes
- NewRegistry (Error)
- Open
- Orient
- ParseExif
- ParsePath
- ParseProfile
- Path.Offset
- Path.Resolve
- Path.Union
- PathBuilder
- PerspectiveCorners
- PixelFormat.BytesPerPixel
- Pixelate
- Pixmap.ClipPath
- Pixmap.ConvertColor
- Pixmap.DrawPolyline
- Pixmap.FillPath
- Pixmap.StrokePath
- Quantize
- RecolorBrush
- RectPath
- Registry
- Resize
- ResizePixmap
- ResizeSize
- Rotate
- Sepia
- SetParallelism
- Source.Bands
- Source.Region
- SplitChannels
- TIFFWriter
- Threshold
- Thumbnail
- ThumbnailBytes
- ThumbnailOp
- Vignette
- WebPOptions
- WebSafePalette
- WithClipPath
- WithDrawBlend
- WithIntent
- WithLinearLight
- WithParallelism
- WithParallelism (Resize)
- WithRegion (Tiff)
- WithScale
Constants ¶
const ( JoinMiter = StrokeJoin(geom.JoinMiter) JoinRound = StrokeJoin(geom.JoinRound) JoinBevel = StrokeJoin(geom.JoinBevel) JoinSquare = StrokeJoin(geom.JoinSquare) )
Stroke joins. A miter longer than MiterLimit times half the width is cut to a bevel (SVG 1.1 section 11.4.4). JoinSquare is the library's own join: the corner is cut flat at half the width from the vertex, so it covers more than a bevel and less than a miter.
const ( CapButt = StrokeCap(geom.CapButt) CapRound = StrokeCap(geom.CapRound) CapSquare = StrokeCap(geom.CapSquare) )
Stroke caps (SVG 1.1 section 11.4.3). Round and square caps lengthen each dash by half the width at both ends; with them a dash of zero length is a dot.
const ( HardMaxDimension = hardMaxDimension HardMaxPixels = hardMaxPixels )
The hard caps as exported values: no limits, not even UnrestrictedLimits, allow a side beyond HardMaxDimension or a frame of more than HardMaxPixels. The library holds frames in memory rather than in tiles, so its second cap is on pixels, not on a tile count.
const ( // MaxFlattenedPoints bounds the points of one flattening; drawing a path // that needs more fails with a [LimitError]. MaxFlattenedPoints = geom.MaxFlattenedPoints // MaxPathCommands bounds the commands of one path. MaxPathCommands = geom.MaxCommands // MaxStrokeWidth bounds a pen's width. MaxStrokeWidth = geom.MaxStrokeWidth // MaxDashEntries bounds the entries of a dash pattern. MaxDashEntries = geom.MaxDashEntries // DefaultFlatnessTolerance is the distance in pixels a flattened curve may // stray from the true curve. DefaultFlatnessTolerance = geom.DefaultTolerance )
Path limits.
const ( // PNGNoCompression stores the data uncompressed. PNGNoCompression = -1 // PNGDefaultCompression is level 6. It is the value 0, so a zero // PNGOptions uses it. PNGDefaultCompression = 0 // PNGBestSpeed is level 1; PNGBestCompression is level 9. PNGBestSpeed = 1 PNGBestCompression = 9 )
Deflate compression levels for PNGOptions.Compression.
const MaxImageBrushPixels = 1 << 26
MaxImageBrushPixels bounds the source region of an image brush.
const MaxPathGradientPoints = 4096
MaxPathGradientPoints bounds the vertices of a path gradient.
const SniffLength = 1024
SniffLength is how many leading bytes Sniff functions are given.
const WebPOff = -1
WebPOff, as the value of a WebPOptions field, means an explicit zero where the field's zero value selects the default.
Variables ¶
var ( // ErrFormat marks data that is not a valid image of its format: a bad // signature, a checksum that does not match, truncation, a field the // specification forbids. Data in no known format is also an ErrFormat. ErrFormat = errors.New("oneimage: invalid image data") // ErrLimit marks a resource bound hit before the work was done: // dimensions, pixel count, frame count, metadata size or expansion ratio. // See [Limits]. ErrLimit = errors.New("oneimage: limit exceeded") // ErrUnsupported marks valid data that uses something the library does // not read or write, or a request it cannot serve. ErrUnsupported = errors.New("oneimage: unsupported") // ErrOperation marks a call that cannot succeed whatever the data is: // an empty image to encode, a size or index out of range, a nil // argument, an option the format has no meaning for. Retrying with the // same arguments fails the same way. ErrOperation = errors.New("oneimage: invalid request") )
The sentinel errors group every failure by what the caller can do about it. Use errors.Is to test for a category and errors.As with *FormatError, *LimitError or *UnsupportedError to read the details.
var ( // Gray8 is 8-bit gray without alpha. Gray8 = PixelFormat{Gray, Uint8, AlphaNone} // GrayAlpha8 is 8-bit gray with straight alpha. GrayAlpha8 = PixelFormat{Gray, Uint8, AlphaStraight} // RGB8 is 8-bit RGB without alpha. RGB8 = PixelFormat{RGB, Uint8, AlphaNone} // NRGBA8 is 8-bit RGB with straight alpha (image.NRGBA). NRGBA8 = PixelFormat{RGB, Uint8, AlphaStraight} // RGBA8 is 8-bit RGB with premultiplied alpha (image.RGBA). RGBA8 = PixelFormat{RGB, Uint8, AlphaPremultiplied} // Gray16 is 16-bit gray without alpha. Gray16 = PixelFormat{Gray, Uint16, AlphaNone} // GrayAlpha16 is 16-bit gray with straight alpha. GrayAlpha16 = PixelFormat{Gray, Uint16, AlphaStraight} // RGB16 is 16-bit RGB without alpha. RGB16 = PixelFormat{RGB, Uint16, AlphaNone} // NRGBA16 is 16-bit RGB with straight alpha (image.NRGBA64). NRGBA16 = PixelFormat{RGB, Uint16, AlphaStraight} // RGBA16 is 16-bit RGB with premultiplied alpha (image.RGBA64). RGBA16 = PixelFormat{RGB, Uint16, AlphaPremultiplied} // CMYK8 is 8-bit CMYK without alpha. CMYK8 = PixelFormat{CMYK, Uint8, AlphaNone} // NRGBAF32 is float32 RGB with straight alpha. NRGBAF32 = PixelFormat{RGB, Float32, AlphaStraight} // GrayF32 is float32 gray without alpha. GrayF32 = PixelFormat{Gray, Float32, AlphaNone} )
Common pixel formats. Alpha follows the standard library's naming: NRGBA formats hold straight (non-premultiplied) alpha, as PNG does, and RGBA formats hold premultiplied colour, as image.RGBA does. Gray has no such ambiguity in package image, so GrayAlpha formats keep one name and are straight.
var ( // CMYK16 is 16-bit CMYK without alpha. CMYK16 = PixelFormat{CMYK, Uint16, AlphaNone} // LabF32 is CIE Lab (D50) in natural units (L 0 to 100) as float32. LabF32 = PixelFormat{Lab, Float32, AlphaNone} // RGBF32 is RGB as float32 without alpha. RGBF32 = PixelFormat{RGB, Float32, AlphaNone} // NRGBAF16 is RGB with straight alpha as half floats. NRGBAF16 = PixelFormat{RGB, Float16, AlphaStraight} // RGBAF32 is RGB with premultiplied alpha as float32. RGBAF32 = PixelFormat{RGB, Float32, AlphaPremultiplied} )
More common pixel formats, beside those in pixel.go.
var ErrSourceChanged = errors.New("oneimage: source changed since it was opened")
ErrSourceChanged marks a source that changed between being opened and its pixels being read. See WithSourceCheck.
var IdentityMatrix = Matrix3x2{1, 0, 0, 1, 0, 0}
IdentityMatrix is the map that changes nothing.
Functions ¶
func BlendRow ¶
func BlendRow(dst, src []float32, mode BlendMode, comp AlphaComposition, opacity float32)
BlendRow blends the source row onto the destination row in place with the blend mode, then the Porter–Duff operator. Both rows hold NRGBA float32 pixels (four values per pixel, 0..1) in the same colour space and must have equal length; opacity in 0..1 scales the source alpha. The result keeps straight alpha; colour under zero alpha is 0. The same kernel, on premultiplied rows, is internal/blend.Row.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/oneimage"
)
func main() {
dst := []float32{1, 0, 0, 1}
src := []float32{0, 0, 1, 0.5}
oneimage.BlendRow(dst, src, oneimage.BlendNormal, oneimage.CompSrcOver, 1)
fmt.Println(dst)
}
Output: [0.5 0 0.5 1]
func BuiltinNames ¶
func BuiltinNames() []string
BuiltinNames lists the names BuiltinProfile accepts.
func Convert ¶
Convert reads an image from r, applies ops to it in order and writes the result to w in the named format (a name or registered extension, see Encode), with that format's default options. It is Decode, Apply and Encode in one call: the image comes upright, all frames go through every op, and the metadata is kept except where an op drops it. A ThumbnailOp among the ops strips the private blocks (Exif, XMP, IPTC, text) as Thumbnail does; without one they are carried to the output.
Example ¶
Convert decodes, applies the operations and encodes in one call. With a thumbnail operation the private metadata blocks are dropped.
package main
import (
"bytes"
"fmt"
"image"
"recursiveai.org/go/oneimage"
)
func main() {
src := oneimage.NewPixmap(image.Rect(0, 0, 40, 20), oneimage.NRGBA8)
png, _ := oneimage.EncodeBytes(src, "png", nil)
var out bytes.Buffer
err := oneimage.Convert(&out, "jpg", bytes.NewReader(png), oneimage.ThumbnailOp(10, 10))
img, _ := oneimage.DecodeBytes(out.Bytes())
fmt.Println(err, img.Format, img.Width(), img.Height())
}
Output: <nil> jpeg 10 5
func ConvertContext ¶
ConvertContext is Convert that stops when ctx is cancelled or its deadline passes, returning ctx.Err(): the context reaches the reading, the decoder, every op and the encoder.
func Describe ¶
Describe returns the operation graph of running ops on img, one line per node, outermost (last) operation first and each input indented two spaces further, ending with the decoded source:
crop(x=1, y=1, width=5, height=5) -> 5x5
gaussian_blur(sigma=1, ...) -> 20x20
decode(format=png, frames=1) -> 40x30
To report each node's size Describe runs the operations on img. An option that was passed to an operation which does not read it (WithDither on a resize, say) is named after the node as `[ignored: WithDither]`; the doc comment of every With option lists the operations that read it.
Example ¶
Describe lists the operation graph, last operation first.
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func opExampleImage(w, h int) *oneimage.Image {
p := oneimage.NewPixmap(image.Rect(0, 0, w, h), oneimage.NRGBA8)
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
p.Set(x, y, color.NRGBA{R: uint8(x * 255 / w), G: uint8(y * 255 / h), B: 128, A: 255})
}
}
return oneimage.NewImage(p)
}
func main() {
img := opExampleImage(40, 30)
lines, _ := oneimage.Describe(img, oneimage.Crop(image.Rect(0, 0, 20, 20)), oneimage.Flip(oneimage.FlipVertical))
for _, l := range lines {
fmt.Println(l)
}
}
Output: flip(axis=vertical) -> 20x20 crop(x=0, y=0, width=20, height=20) -> 20x20 decode(format=none, frames=1) -> 40x30
Example (IgnoredOptions) ¶
Describe names the options an operation was given but does not read.
package main
import (
"fmt"
"image"
"recursiveai.org/go/oneimage"
)
func main() {
img := oneimage.NewImage(oneimage.NewPixmap(image.Rect(0, 0, 8, 8), oneimage.NRGBA8))
lines, _ := oneimage.Describe(img, oneimage.Resize(4, 4, oneimage.WithDither(oneimage.DitherNone)))
fmt.Println(lines[0])
}
Output: resize(width=4, height=4, fit=contain, anchor=center, upscale=True, filter=auto, linear=True, background=[0, 0, 0, 0]) -> 4x4 [ignored: WithDither]
func Encode ¶
Encode writes img in the named format, given as a name or a registered extension ("png", "jpg", ".tif"; see LookupFormat). img may be any image.Image; an *Image brings its frames, metadata and format details along. opts is nil for the defaults or the format's options type (*PNGOptions for "png").
Before the encoder runs, the Exif block of an *Image is corrected for the image's size and orientation (see ExifForOutput); a block that cannot be parsed is dropped rather than written with stale tags. Encoders that list the pixel formats they take (see InfoEncoder) get frames converted to the best of them.
func EncodeBMP ¶
EncodeBMP writes img as BMP. opts may be nil for the defaults. It is Encode with the "bmp" format.
Example ¶
package main
import (
"bytes"
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func main() {
m := image.NewNRGBA(image.Rect(0, 0, 3, 2))
m.SetNRGBA(1, 1, color.NRGBA{R: 10, G: 20, B: 30, A: 255})
var buf bytes.Buffer
if err := oneimage.EncodeBMP(&buf, m, &oneimage.BMPOptions{BitsPerPixel: 24}); err != nil {
panic(err)
}
got, err := oneimage.DecodeBytes(buf.Bytes())
if err != nil {
panic(err)
}
fmt.Println(got.Format, got.Width(), got.Height(), got.Details.(*oneimage.BMPInfo).BitsPerPixel, got.At(1, 1))
}
Output: bmp 3 2 24 {10 20 30 255}
func EncodeBytes ¶
EncodeBytes is Encode into a new byte slice.
func EncodeBytesContext ¶
func EncodeBytesContext(ctx context.Context, img image.Image, format string, opts any, eopts ...EncodeOption) ([]byte, error)
EncodeBytesContext is EncodeBytes with the cancellation of EncodeContext.
func EncodeContext ¶
func EncodeContext(ctx context.Context, w io.Writer, img image.Image, format string, opts any, eopts ...EncodeOption) error
EncodeContext is Encode that stops when ctx is cancelled: the context is checked before encoding starts and at every write to w, so an encoder that writes as it goes is interrupted within one buffer, and it is passed to a encoder as EncodeRequest.Context. The error is ctx.Err().
func EncodeGIF ¶
EncodeGIF writes img as GIF; an animation for an *Image with several frames. opts may be nil for the defaults. It is Encode with the "gif" format.
Example ¶
package main
import (
"bytes"
"fmt"
"image"
"image/color"
"time"
"recursiveai.org/go/oneimage"
)
func main() {
// Two frames of a red square moving over a transparent screen.
img := &oneimage.Image{LoopCount: 0}
for i := 0; i < 2; i++ {
m := image.NewNRGBA(image.Rect(0, 0, 8, 8))
for y := 2; y < 5; y++ {
for x := 1 + 2*i; x < 4+2*i; x++ {
m.SetNRGBA(x, y, color.NRGBA{R: 255, A: 255})
}
}
img.Frames = append(img.Frames, oneimage.Frame{Image: m, Delay: 100 * time.Millisecond})
}
var buf bytes.Buffer
if err := oneimage.EncodeGIF(&buf, img, &oneimage.GIFOptions{FrameDifferencing: true}); err != nil {
panic(err)
}
got, err := oneimage.DecodeBytes(buf.Bytes())
if err != nil {
panic(err)
}
fmt.Println(got.Format, got.Width(), got.Height(), len(got.Frames), got.Frames[1].Delay, got.LoopCount)
}
Output: gif 8 8 2 100ms 0
func EncodeICO ¶
EncodeICO writes img as an icon file; each frame of an *Image becomes an entry. opts may be nil for the defaults. It is Encode with the "ico" format.
Example ¶
package main
import (
"bytes"
"fmt"
"image"
"recursiveai.org/go/oneimage"
)
func main() {
img := &oneimage.Image{}
for _, s := range []int{16, 32} {
img.Frames = append(img.Frames, oneimage.Frame{Image: image.NewNRGBA(image.Rect(0, 0, s, s))})
}
var buf bytes.Buffer
if err := oneimage.EncodeICO(&buf, img, nil); err != nil {
panic(err)
}
got, err := oneimage.DecodeBytes(buf.Bytes())
if err != nil {
panic(err)
}
for _, f := range got.Frames {
fmt.Println(f.Image.Bounds().Dx(), f.Image.Bounds().Dy())
}
}
Output: 16 16 32 32
func EncodeJPEG ¶
EncodeJPEG writes img as JPEG. opts may be nil for the defaults. It is Encode with the "jpeg" format.
Example ¶
package main
import (
"bytes"
"fmt"
"image"
"recursiveai.org/go/oneimage"
)
func main() {
src := image.NewNRGBA(image.Rect(0, 0, 32, 16))
for i := range src.Pix {
src.Pix[i] = 200
}
var buf bytes.Buffer
err := oneimage.EncodeJPEG(&buf, src, &oneimage.JPEGOptions{Quality: 90, Subsampling: oneimage.JPEGSubsample444})
info, _ := oneimage.IdentifyBytes(buf.Bytes())
ji := info.Details.(*oneimage.JPEGInfo)
fmt.Println(err, info.Format, info.Width, info.Height, ji.Components[0].H, ji.Progressive)
}
Output: <nil> jpeg 32 16 1 false
func EncodePNG ¶
EncodePNG writes img as PNG (APNG when it has several frames). opts may be nil for the defaults. It is Encode with the "png" format.
Example (Indexed) ¶
package main
import (
"bytes"
"fmt"
"image"
"recursiveai.org/go/oneimage"
)
func main() {
src := image.NewNRGBA(image.Rect(0, 0, 8, 8))
for i := range src.Pix {
src.Pix[i] = uint8(i * 5)
}
var buf bytes.Buffer
err := oneimage.EncodePNG(&buf, src, &oneimage.PNGOptions{Color: oneimage.PNGColorIndexed, MaxColors: 4})
info, _ := oneimage.IdentifyBytes(buf.Bytes())
pi := info.Details.(*oneimage.PNGInfo)
fmt.Println(err, pi.ColorType, pi.BitDepth)
}
Output: <nil> 3 2
func EncodeTIFF ¶
EncodeTIFF writes img as TIFF, one page per frame. opts may be nil for the defaults. It is Encode with the "tiff" format.
Example ¶
package main
import (
"bytes"
"fmt"
"image"
"recursiveai.org/go/oneimage"
)
func main() {
pages := &oneimage.Image{Frames: []oneimage.Frame{
{Image: image.NewGray(image.Rect(0, 0, 8, 4))},
{Image: image.NewNRGBA(image.Rect(0, 0, 2, 2))},
}}
var buf bytes.Buffer
opts := &oneimage.TIFFOptions{Compression: oneimage.TIFFCompressionLZW, Predictor: true}
if err := oneimage.EncodeTIFF(&buf, pages, opts); err != nil {
panic(err)
}
img, err := oneimage.Decode(&buf)
if err != nil {
panic(err)
}
for i, f := range img.All() {
fmt.Println(i, f.Image.Bounds().Size())
}
ti := img.Details.(*oneimage.TIFFInfo)
fmt.Println(ti.Pages[0].Compression, ti.Pages[0].Predictor)
}
Output: 0 (8,4) 1 (2,2) lzw 2
func EncodeWebP ¶
EncodeWebP writes img as WebP. opts may be nil for the defaults.
Example ¶
package main
import (
"bytes"
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func main() {
// A picture with a flat background and a block of detail.
src := image.NewNRGBA(image.Rect(0, 0, 32, 32))
for y := 0; y < 32; y++ {
for x := 0; x < 32; x++ {
c := color.NRGBA{R: 200, G: 220, B: 255, A: 255}
if x >= 8 && x < 24 && y >= 8 && y < 24 {
c = color.NRGBA{R: uint8(x * 8), G: uint8(y * 8), B: 40, A: 255}
}
src.SetNRGBA(x, y, c)
}
}
// Lossless output reads back exactly.
var buf bytes.Buffer
if err := oneimage.EncodeWebP(&buf, src, &oneimage.WebPOptions{Lossless: true}); err != nil {
fmt.Println(err)
return
}
img, err := oneimage.Decode(&buf)
if err != nil {
fmt.Println(err)
return
}
info := img.Details.(*oneimage.WebPInfo)
fmt.Println(img.Format, img.Width(), img.Height(), "lossless:", info.Lossless)
fmt.Println(img.At(3, 3) == src.At(3, 3), img.At(12, 20) == src.At(12, 20))
// Lossy output is much smaller and close to the source.
buf.Reset()
if err := oneimage.EncodeWebP(&buf, src, &oneimage.WebPOptions{Quality: 80}); err != nil {
fmt.Println(err)
return
}
img, _ = oneimage.Decode(&buf)
fmt.Println("lossless:", img.Details.(*oneimage.WebPInfo).Lossless)
}
Output: webp 32 32 lossless: true true true lossless: false
func ExifForOutput ¶
ExifForOutput returns a copy of an Exif block with its size and orientation tags set for an image of the given size and orientation: Orientation in the first IFD and PixelXDimension and PixelYDimension in the Exif IFD, each rewritten in place when present (absent tags are not added), so every other tag and offset is untouched. The result never carries the "Exif\0\0" prefix. An empty block gives nil. A block that cannot be parsed is a FormatError; an orientation outside 1 to 8 is an ErrOperation.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/oneimage"
)
func main() {
exif := []byte("II*\x00\x08\x00\x00\x00\x01\x00\x12\x01\x03\x00\x01\x00\x00\x00\x06\x00\x00\x00\x00\x00")
// The pixels have been turned upright: the block must say so.
out, _ := oneimage.ExifForOutput(exif, 18, 24, 1)
f, _ := oneimage.ParseExif(out)
fmt.Println(f.Orientation)
}
Output: 1
func ExifOrientation ¶
ExifOrientation returns the orientation (1 to 8) stored in an Exif block (a TIFF stream as found in Metadata.Exif), or 1 when it holds none or is malformed. Only the SHORT form the Exif standard defines is read.
func FitRenderSize ¶
FitRenderSize resolves a requested raster size for a resolution-independent picture whose natural size is natW by natH (in pixels, possibly fractional). It is the rule behind WithRenderSize, DecodeRequest.RenderSize and the render options of the svg and metafile packages:
- both sides zero: the natural size, each side rounded up;
- one side zero: that side follows the natural aspect ratio, rounded up;
- both sides given: used as they are (the picture is stretched to fit);
- a negative side: an error wrapping ErrOperation.
Every result side is at least 1. A natural size that is not positive and finite is treated as 1 by 1.
func FormatNames ¶
func FormatNames() []string
FormatNames returns the names of the registered formats, sorted.
func FormatOp ¶
FormatOp writes op as `name(parameter=value, ...)` with the parameters in the order Params gives them. Booleans read True or False, colours [r, g, b, a], enumerated values are lower-case words.
func Parallelism ¶
func Parallelism() int
Parallelism returns the effective limit set by SetParallelism: the number of goroutines one operation may use.
func RegisterFormat ¶
func RegisterFormat(f Format)
RegisterFormat adds a format. It panics on an empty or duplicate name or a missing Sniff, since those are programming errors found at start-up.
func ResizePixmap ¶
ResizePixmap scales src into dst, which fixes the output size and format: the source is stretched to dst's bounds (use ResizeSize to find the size that keeps an aspect ratio) and converted to dst's pixel format. Options read: WithFilter, WithLinear, WithLimits. It lets a caller that resizes many images of one size reuse their output buffers.
Example ¶
package main
import (
"fmt"
"image"
"recursiveai.org/go/oneimage"
)
func main() {
src := oneimage.NewPixmap(image.Rect(0, 0, 100, 60), oneimage.RGB8)
dst := oneimage.NewPixmap(image.Rect(0, 0, 10, 6), oneimage.RGB8)
fmt.Println(oneimage.ResizePixmap(dst, src), dst.Bounds().Size())
}
Output: <nil> (10,6)
func ResizeSize ¶
ResizeSize returns the size Resize gives an sw by sh image for the box width by height, without touching pixels: the size the scaling lands on before any crop or padding.
Example ¶
A width or a height alone keeps the aspect ratio.
package main
import (
"fmt"
"recursiveai.org/go/oneimage"
)
func main() {
w, h, _ := oneimage.ResizeSize(64, 48, 25, 0, oneimage.FitContain, true)
fmt.Println(w, h)
}
Output: 25 19
func SetColorCacheBudget ¶
func SetColorCacheBudget(bytes int64)
SetColorCacheBudget sets the byte budget of the transform cache (default 32 MiB). Each entry is charged the size of both profiles plus 64 KiB for its curves; a transform larger than the budget is used but not kept. A budget of zero or less disables caching.
func SetParallelism ¶
func SetParallelism(n int)
SetParallelism sets the process-wide default for how many goroutines one resize, filter, composite, colour conversion, decode or encode uses; a call that passes WithParallelism uses that instead. n <= 0 (the default) means runtime.GOMAXPROCS. It is safe to call while other goroutines are running operations: a running call keeps the value it started with, and the next one sees the new value. The setting changes speed only: results are identical for every value.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/oneimage"
)
func main() {
oneimage.SetParallelism(2)
fmt.Println(oneimage.Parallelism())
oneimage.SetParallelism(0)
}
Output: 2
func WebSafePalette ¶
WebSafePalette returns the 139 distinct named colours of CSS Color 4 that QuantizerWebSafe uses, opaque, in the order the quantizer indexes them. Pass it to DitherToPalette to map an image onto it.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/oneimage"
)
func main() {
p := oneimage.WebSafePalette()
fmt.Println(len(p), len(oneimage.WernerPalette()))
}
Output: 139 110
func WernerPalette ¶
WernerPalette returns the 110 colours of QuantizerWerner (Werner's Nomenclature of Colours), opaque, in the order the quantizer indexes them.
Types ¶
type AlphaComposition ¶
type AlphaComposition uint8
AlphaComposition is a Porter–Duff operator: how source and backdrop coverage combine.
const ( CompSrcOver AlphaComposition = iota CompDestOver CompClear CompSrc CompDest CompSrcIn CompDestIn CompSrcOut CompDestOut CompSrcAtop CompDestAtop CompXor CompPlus )
The operators; CompSrcOver, the zero value, is the usual "paint on top".
func ParseAlphaComposition ¶
func ParseAlphaComposition(s string) (AlphaComposition, error)
ParseAlphaComposition reads an operator name as String writes it.
func (AlphaComposition) MarshalText ¶
func (v AlphaComposition) MarshalText() ([]byte, error)
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (AlphaComposition) String ¶
func (a AlphaComposition) String() string
String returns the name of the AlphaComposition, spelled as its text form and Parse function read it.
func (*AlphaComposition) UnmarshalText ¶
func (v *AlphaComposition) UnmarshalText(text []byte) error
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type AlphaMode ¶
type AlphaMode uint8
AlphaMode says whether a pixel has an alpha channel and how colour relates to it.
const ( // AlphaNone: no alpha channel; every pixel is opaque. AlphaNone AlphaMode = iota // AlphaStraight: colour channels are independent of alpha (what PNG, // WebP and TIFF unassociated alpha store). AlphaStraight // AlphaPremultiplied: colour channels are already multiplied by alpha // (what the standard library's image.RGBA holds). Ops compute in this form. AlphaPremultiplied )
Alpha modes. The alpha channel, when present, is the last channel.
func (AlphaMode) MarshalText ¶
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (AlphaMode) String ¶
String returns the name of the AlphaMode, spelled as its text form and Parse function read it.
func (*AlphaMode) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type AnalysisOption ¶
type AnalysisOption func(*analysisConfig)
AnalysisOption adjusts Image.Histogram and Image.Statistics.
func SkipTransparent ¶
func SkipTransparent() AnalysisOption
SkipTransparent leaves out pixels whose alpha is 0 (images without alpha are unaffected).
type Anchor ¶
type Anchor uint8
Anchor places a smaller box inside a bigger one: the image on a padded canvas, or the window kept by a cover crop.
const ( AnchorCenter Anchor = iota AnchorTopLeft AnchorTop AnchorTopRight AnchorLeft AnchorRight AnchorBottomLeft AnchorBottom AnchorBottomRight AnchorSmart )
The anchors. AnchorSmart only matters for a cover crop, where it picks the window with the most detail (the largest sum of Sobel gradient magnitudes of the luma, ties to the window nearest the centre); everywhere else it behaves like AnchorCenter. A difference that does not split evenly rounds the offset down.
func ParseAnchor ¶
ParseAnchor reads an anchor name as String writes it.
func (Anchor) MarshalText ¶
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (Anchor) String ¶
String returns the name of the Anchor, spelled as its text form and Parse function read it.
func (*Anchor) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type Axis ¶
type Axis uint8
Axis names the direction of a Flip.
The flip axes: FlipHorizontal mirrors left to right, FlipVertical top to bottom.
func (Axis) MarshalText ¶
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (Axis) String ¶
String returns the name of the Axis, spelled as its text form and Parse function read it.
func (*Axis) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type BMPInfo ¶
type BMPInfo struct {
// HeaderSize is the size of the info header: 12 (core), 16 or 64 (OS/2 2.x),
// 40, 52, 56, 108 (version 4) or 124 (version 5).
HeaderSize int
// BitsPerPixel is 1, 4, 8, 16, 24 or 32.
BitsPerPixel int
// Compression is the stored value: 0 uncompressed, 1 RLE8, 2 RLE4,
// 3 bit fields, 6 bit fields with alpha.
Compression uint32
// TopDown reports that rows are stored from the top (negative height).
TopDown bool
// PaletteEntries is the number of colours in the colour table.
PaletteEntries int
// Masks are the red, green, blue and alpha channel masks of a bit-field
// image, zero where there are none.
Masks [4]uint32
}
BMPInfo holds the facts a BMP file states about itself. Decoding fills it in Image.Details and Info.Details.
type BMPOptions ¶
type BMPOptions struct {
// BitsPerPixel is 0, 24 (alpha is dropped) or 32. Zero follows the pixel
// format, in [EncodeBMP] and [NewBMPWriter] alike: 32 for a format with
// an alpha channel, whether or not any pixel is transparent, and 24 for
// one without.
BitsPerPixel int
// StripMetadata leaves out the ICC profile that would otherwise be
// embedded.
StripMetadata bool
// TopDown stores the rows from the top and writes the height as a negative
// number. The default is the usual bottom-up order. Every common reader
// handles both. [BMPWriter] honours it too: a top-down file can be
// streamed to any io.Writer, a bottom-up one needs an io.WriteSeeker.
TopDown bool
}
BMPOptions configures the BMP encoder. The zero value is the default.
type BMPWriter ¶
type BMPWriter struct {
// contains filtered or unexported fields
}
BMPWriter writes one BMP image a band of rows at a time, holding only the band being converted, so an image taller than memory allows can be written as it is produced.
Bands always arrive from the top of the image down, as with the other streaming writers. A BMP normally stores its bottom row first, so the default file (bottom-up, as EncodeBMP writes it) needs a destination that is an io.WriteSeeker: each band's rows are written at their final offsets, which are known because rows have a fixed size. With BMPOptions.TopDown set the file is the top-down form (a negative height in the header), rows are written in the order they come and any io.Writer will do. Either way the bytes are those EncodeBMP writes for the same pixels and options. The file size and pixel data size fields are written correctly in the header, which is possible because the size is declared up front.
Example ¶
A top-down BMP written a band at a time to any writer. Bands always come from the top of the image; the default bottom-up file needs an io.WriteSeeker instead.
package main
import (
"bytes"
"fmt"
"image"
"recursiveai.org/go/oneimage"
)
func main() {
var buf bytes.Buffer
bw, err := oneimage.NewBMPWriter(&buf, 8, 6, oneimage.RGB8, &oneimage.BMPOptions{BitsPerPixel: 24, TopDown: true}, oneimage.Metadata{})
if err != nil {
fmt.Println(err)
return
}
band := oneimage.NewPixmap(image.Rect(0, 0, 8, 3), oneimage.RGB8)
for range 2 {
if err := bw.WriteRows(band); err != nil {
fmt.Println(err)
return
}
}
if err := bw.Close(); err != nil {
fmt.Println(err)
return
}
img, err := oneimage.DecodeBytes(buf.Bytes())
if err != nil {
fmt.Println(err)
return
}
fmt.Println(img.Bounds().Dx(), img.Bounds().Dy(), buf.Len())
}
Output: 8 6 198
func NewBMPWriter ¶
func NewBMPWriter(w io.Writer, width, height int, format PixelFormat, opts *BMPOptions, meta Metadata) (*BMPWriter, error)
NewBMPWriter starts a BMP of width x height pixels of the given pixel format and writes the headers. Bands written later are converted to straight 8-bit RGBA first; the format says whether they carry alpha. opts may be nil. BitsPerPixel 0 means 32 when format has alpha and 24 when it does not, as in EncodeBMP; 32 bits are written as straight alpha with the version 4 header. TopDown chooses the form of the file: without it (the default) w must also implement io.WriteSeeker, found by type assertion so that a top-down file can go to a plain io.Writer; otherwise NewBMPWriter returns an ErrOperation saying so. Bands come top to bottom either way (see BMPWriter). meta supplies the ICC profile (embedded after the pixels, with the version 5 header) unless opts.StripMetadata. Files of 4 GiB or more are a LimitError. Bands are converted to straight 8-bit RGBA first (premultiplied alpha is divided out).
func (*BMPWriter) Close ¶
Close finishes the image: fewer rows than the declared height is an error; otherwise the ICC profile, if any, is written after the pixels. It does not close the destination. Calling it again returns the first call's result.
func (*BMPWriter) WriteBands ¶
WriteBands writes every band of seq with BMPWriter.WriteRows. It does not close the writer: call BMPWriter.Close afterwards. It stops at the first error, which is returned (a band error from the sequence included).
type BackdropBrush ¶
type BackdropBrush interface {
Brush
// FillRowOver is FillRow with the backdrop of the same run (NRGBA
// floats in the image's encoded values) passed in.
FillRowOver(x, y int, backdrop, rgba []float32)
}
BackdropBrush is a Brush that needs the pixels already there, as Recolor does.
type BlendMode ¶
type BlendMode uint8
BlendMode is how a source colour combines with the backdrop colour under it before the alpha operator is applied. The separable modes follow the W3C Compositing and Blending Level 1 definitions (section 10.1) and the non-separable ones its section 10.2; the modes that specification omits use the Photoshop definitions.
const ( BlendNormal BlendMode = iota BlendMultiply BlendScreen BlendOverlay BlendDarken BlendLighten BlendColorDodge BlendColorBurn BlendHardLight BlendSoftLight BlendDifference BlendExclusion BlendAdd BlendLinearDodge BlendSubtract BlendLinearBurn BlendVividLight BlendLinearLight BlendPinLight BlendHardMix BlendDivide BlendHue BlendSaturation BlendColor BlendLuminosity )
The blend modes. BlendNormal, the zero value, shows the source colour. BlendAdd and BlendLinearDodge are the same mode under two names.
func ParseBlendMode ¶
ParseBlendMode reads a blend mode name as String writes it.
func (BlendMode) MarshalText ¶
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (BlendMode) String ¶
String returns the name of the BlendMode, spelled as its text form and Parse function read it.
func (*BlendMode) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type BlindnessMode ¶
type BlindnessMode uint8
BlindnessMode names a colour-vision deficiency for ColorBlindness.
const ( Protanopia BlindnessMode = iota Protanomaly Deuteranopia Deuteranomaly Tritanopia Tritanomaly Achromatopsia Achromatomaly )
The modes: the -opia ones are the complete deficiencies, the -omaly ones their milder anomalous forms, and achromatopsia (and its milder form) the absence of colour vision.
func ParseBlindnessMode ¶
func ParseBlindnessMode(s string) (BlindnessMode, error)
ParseBlindnessMode reads a mode name as String writes it.
func (BlindnessMode) MarshalText ¶
func (v BlindnessMode) MarshalText() ([]byte, error)
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (BlindnessMode) String ¶
func (m BlindnessMode) String() string
String returns the name of the BlindnessMode, spelled as its text form and Parse function read it.
func (*BlindnessMode) UnmarshalText ¶
func (v *BlindnessMode) UnmarshalText(text []byte) error
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type BooleanOp ¶
type BooleanOp uint8
BooleanOp is a set operation on the regions two paths enclose.
const ( // BoolUnion keeps what either path encloses. BoolUnion BooleanOp = iota // BoolIntersection keeps what both enclose. BoolIntersection // BoolDifference keeps what the subject encloses and the clip does not. BoolDifference // BoolXor keeps what exactly one encloses. BoolXor )
Boolean operations.
func (BooleanOp) MarshalText ¶
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (*BooleanOp) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type BrightnessMode ¶
type BrightnessMode uint8
BrightnessMode selects the formula of BrightnessContrast.
const ( BrightnessLinear BrightnessMode = iota BrightnessPhotoshopLegacy BrightnessPhotoshopSmooth )
The modes. BrightnessLinear is the default: a slope of tan((contrast+1)·π/4) about mid-gray plus the brightness offset. BrightnessPhotoshopLegacy is the integer-era formula (contrast cut to 1/255 steps, brightness scaled by 150). BrightnessPhotoshopSmooth is a soft-knee approximation of the current Photoshop control: it follows the linear formula through a smooth S-shaped ease, and is the identity when both settings are zero.
func ParseBrightnessMode ¶
func ParseBrightnessMode(s string) (BrightnessMode, error)
ParseBrightnessMode reads a mode name as String writes it.
func (BrightnessMode) MarshalText ¶
func (v BrightnessMode) MarshalText() ([]byte, error)
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (BrightnessMode) String ¶
func (m BrightnessMode) String() string
String returns the name of the BrightnessMode, spelled as its text form and Parse function read it.
func (*BrightnessMode) UnmarshalText ¶
func (v *BrightnessMode) UnmarshalText(text []byte) error
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type Brush ¶
type Brush interface {
// FillRow writes straight (not premultiplied) float RGBA in 0..1, in the
// image's own encoded values, for the run of len(rgba)/4 pixels that starts
// at column x of row y. Rows are asked for at any coordinate; a brush must
// not panic or produce NaN for any of them.
FillRow(x, y int, rgba []float32)
}
Brush supplies the colour of the pixels a fill or stroke covers, one row at a time. It never sees geometry: the rasteriser decides how much of each pixel is covered and the brush says what colour goes there.
A Brush works in the pixel grid of the image it paints and does not move with the shape, so two fills with one brush line up. Implement the interface to paint something the built-in brushes do not; FillRow may be called for different rows concurrently in later versions and must give the same numbers for the same pixel every time.
func EllipticGradientBrush ¶
func EllipticGradientBrush(centre, axisEnd Vec2, axisRatio float64, stops []Stop, opts ...BrushOption) (Brush, error)
EllipticGradientBrush paints the normalised distance in an ellipse around centre whose first axis runs to axisEnd and whose other axis is axisRatio times as long; with WithSquaredDistance the square of the distance.
func HatchBrush ¶
func HatchBrush(style HatchStyle, foreground, background color.NRGBA, opts ...BrushOption) (Brush, error)
HatchBrush tiles one of the built-in 4 by 4 hatch patterns: foreground where the style draws, background elsewhere (transparent black by default).
Example ¶
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func must[T any](v T, err error) T {
if err != nil {
panic(err)
}
return v
}
func main() {
pm := oneimage.NewPixmap(image.Rect(0, 0, 4, 4), oneimage.Gray8)
b := must(oneimage.HatchBrush(oneimage.HatchHorizontal, color.NRGBA{255, 255, 255, 255}, color.NRGBA{0, 0, 0, 255}))
if err := pm.FillPath(b, must(oneimage.RectPath(0, 0, 4, 4))); err != nil {
panic(err)
}
fmt.Println(pm.Pix8[0], pm.Pix8[4], pm.Pix8[8], pm.Pix8[12])
}
Output: 0 255 0 0
func ImageBrush ¶
func ImageBrush(src image.Image, opts ...BrushOption) (Brush, error)
ImageBrush paints with the pixels of src, repeated (or placed once with WithoutTiling). The source is read once, at construction, as straight RGBA; a region over 2^26 pixels is refused. Anchoring is in the image: the source's top-left pixel sits at the image origin plus WithSourceOffset.
func LinearGradientBrush ¶
func LinearGradientBrush(start, end Vec2, stops []Stop, opts ...BrushOption) (Brush, error)
LinearGradientBrush paints the position of the projection of each pixel centre on the line from start to end, mapped through the stops. Stops are sorted by position (stably, so two stops at one position make a hard edge); before the first stop the first colour holds and after the last the last, unless WithRepetition says otherwise. Colours blend in the image's encoded values, premultiplied by alpha (see WithStraightBlend), or in linear light in a linear fill. start and end are in brush space (see WithBrushTransform) and must differ.
Example ¶
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func must[T any](v T, err error) T {
if err != nil {
panic(err)
}
return v
}
func main() {
pm := oneimage.NewPixmap(image.Rect(0, 0, 4, 1), oneimage.NRGBA8)
b := must(oneimage.LinearGradientBrush(oneimage.Vec2{0, 0}, oneimage.Vec2{4, 0}, []oneimage.Stop{
{Position: 0, Color: color.NRGBA{0, 0, 0, 255}},
{Position: 1, Color: color.NRGBA{255, 255, 255, 255}},
}))
if err := pm.FillPath(b, must(oneimage.RectPath(0, 0, 4, 1))); err != nil {
panic(err)
}
for x := 0; x < 4; x++ {
fmt.Print(pm.Pix8[4*x], " ")
}
fmt.Println()
}
Output: 32 96 159 223
func PathGradientBrush ¶
PathGradientBrush blends the vertex colours barycentrically over the triangles (centre, point i, point i+1), wrapping at the end; pixels outside them are transparent. The default centre is the centroid of the points with the mean of the colours (see WithPathGradientCentre). It takes between 3 and 4096 points, one colour each, and evaluates at pixel centres in the image's grid.
func PatternBrush ¶
func PatternBrush(cells [][]bool, foreground, background color.NRGBA, opts ...BrushOption) (Brush, error)
PatternBrush tiles a two-colour bitmap. cells is indexed [row][column]; every row must have the same non-zero length. Each pixel takes the cell under its centre in pattern space (see WithBrushTransform), without smoothing.
func RadialGradientBrush ¶
func RadialGradientBrush(centre Vec2, radius float64, stops []Stop, opts ...BrushOption) (Brush, error)
RadialGradientBrush paints the distance from centre divided by radius. With WithFocal it is a two-circle gradient as SVG 2 defines it. radius must be positive.
func RecolorBrush ¶
RecolorBrush paints the target colour where the pixels already there are close to the source colour. With d the Euclidean distance between a pixel and source over straight R, G, B, A in 0..1, the strength is max(0, 1 - d*d / (4*threshold)): 1 for an exact match, 0 from d = 2*sqrt(threshold); the pixel then becomes the target painted with its alpha times that strength. A threshold of 0 changes exact matches only. In a linear-light fill the comparison happens in linear light.
Example ¶
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func must[T any](v T, err error) T {
if err != nil {
panic(err)
}
return v
}
func main() {
pm := oneimage.NewPixmap(image.Rect(0, 0, 2, 1), oneimage.NRGBA8)
pm.Set(0, 0, color.NRGBA{200, 40, 40, 255})
pm.Set(1, 0, color.NRGBA{40, 40, 200, 255})
b := must(oneimage.RecolorBrush(color.NRGBA{200, 40, 40, 255}, color.NRGBA{0, 255, 0, 255}, 0))
if err := pm.FillPath(b, must(oneimage.RectPath(0, 0, 2, 1))); err != nil {
panic(err)
}
fmt.Println(pm.Pix8[0:4], pm.Pix8[4:8])
}
Output: [0 255 0 255] [40 40 200 255]
type BrushOption ¶
type BrushOption func(*brushOpts)
BrushOption adjusts a brush constructor; options a constructor has no use for are ignored.
func WithBrushTransform ¶
func WithBrushTransform(m Matrix3x2) BrushOption
WithBrushTransform places the brush's own space in the image by an affine map: the position of a pixel is that of its centre taken back through the inverse. Gradients take their geometry in gradient space, patterns and image brushes their cells and source pixels. The default is the identity.
func WithFocal ¶
func WithFocal(focal Vec2, focalRadius float64) BrushOption
WithFocal makes a radial gradient a two-circle gradient (SVG 2): the colour position is where the circle growing linearly from (focal, focalRadius) to the gradient's own circle passes through the pixel, the larger position with a non-negative radius winning. A focal circle outside the end circle makes a cone, outside which pixels are transparent.
func WithPathGradientCentre ¶
func WithPathGradientCentre(p Vec2, c color.NRGBA) BrushOption
WithPathGradientCentre sets the point and colour a path gradient blends towards; by default the centroid of the points and the mean of the colours.
func WithRepetition ¶
func WithRepetition(r Repetition) BrushOption
WithRepetition sets what a gradient does outside 0..1 (default GradientClamp).
func WithSampling ¶
func WithSampling(s Sampling) BrushOption
WithSampling sets how an image brush reads its source (default SampleNearest).
func WithSourceOffset ¶
func WithSourceOffset(dx, dy float64) BrushOption
WithSourceOffset moves an image brush's source by (dx, dy) pixels (after the brush transform).
func WithSourceRegion ¶
func WithSourceRegion(r image.Rectangle) BrushOption
WithSourceRegion limits an image brush to a rectangle of its source.
func WithSquaredDistance ¶
func WithSquaredDistance() BrushOption
WithSquaredDistance makes an elliptic gradient use the square of the normalised distance as the position.
func WithStraightBlend ¶
func WithStraightBlend() BrushOption
WithStraightBlend makes a gradient blend straight (not premultiplied) colours. By default stops blend premultiplied by alpha, so red fading to transparent blue stays red as it fades; straight blending passes through purple. The two agree when every stop is opaque.
func WithoutTiling ¶
func WithoutTiling() BrushOption
WithoutTiling places an image brush's source once instead of repeating it.
type Capabilities ¶
type Capabilities uint32
Capabilities lists the hints a Decoder honours itself. The core only sends a hint a decoder declares; for the others it falls back (cropping after the decode) or refuses.
const ( // CapRegion: the decoder decodes only [DecodeRequest.Region]. CapRegion Capabilities = 1 << iota // CapScale: the decoder can decode at 1/ScaleDenominator size directly // (JPEG's DCT scaling, for example), cheaper than decode-then-resize. CapScale // CapRenderSize: the format is vector or resolution independent and the // decoder rasterises at [DecodeRequest.RenderSize] (SVG, metafiles, // PDF pages). CapRenderSize // CapRandomAccess: the decoder reads any part of a frame without decoding // the rest (tiled or block-structured data), so region reads are cheap. // It implies CapRegion: the core sends regions to such a decoder. CapRandomAccess )
type Channel ¶
type Channel uint8
Channel names the colour channel a per-channel tone operation works on.
The channels. ChannelAll, the zero value, is every colour channel; a gray image accepts only ChannelAll.
func ParseChannel ¶
ParseChannel reads a channel name as String writes it.
func (Channel) MarshalText ¶
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (Channel) String ¶
String returns the name of the Channel, spelled as its text form and Parse function read it.
func (*Channel) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type ChannelStats ¶
type ChannelStats struct {
// Count is the number of samples counted.
Count int
// Min is the smallest sample.
Min float64
// Max is the largest sample.
Max float64
// Mean and StdDev are the average and the population standard deviation.
Mean, StdDev float64
}
ChannelStats summarises one channel, in sample units (0..255 at 8 bits, 0..65535 at 16).
type ColorMatrix ¶
type ColorMatrix [20]float64
ColorMatrix is a 5 by 4 colour matrix in row-major order: a pixel (r, g, b, a, 1) is multiplied from the left, so row 0 says how much red every output channel gets and row 4 holds the offsets. It works on straight colour in 0..1, and the result is clamped.
func ColorMatrixColorBlindness ¶
func ColorMatrixColorBlindness(mode BlindnessMode) ColorMatrix
ColorMatrixColorBlindness returns the matrix that simulates a deficiency on stored (encoded) values. Achromatopsia is gray by the BT.601 weights 0.299, 0.587 and 0.114; the anomalous forms blend the complete matrix 60:40 with the identity.
func ColorMatrixIdentity ¶
func ColorMatrixIdentity() ColorMatrix
ColorMatrixIdentity returns the matrix that changes nothing.
func ColorMatrixOpacity ¶
func ColorMatrixOpacity(amount float64) ColorMatrix
ColorMatrixOpacity returns the matrix that multiplies alpha by amount.
func ColorMatrixSepia ¶
func ColorMatrixSepia(amount float64) ColorMatrix
ColorMatrixSepia returns the sepia tone matrix blended with the identity by amount (0 is the identity, 1 full sepia).
func (ColorMatrix) At ¶
func (m ColorMatrix) At(row, col int) float64
At returns the item in row (0..4) and column (0..3).
func (ColorMatrix) IsIdentity ¶
func (m ColorMatrix) IsIdentity() bool
IsIdentity reports whether the matrix changes nothing.
func (ColorMatrix) Then ¶
func (m ColorMatrix) Then(n ColorMatrix) ColorMatrix
Then returns the matrix that applies m first and n second.
Example ¶
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func toneExampleImage() *oneimage.Image {
p := oneimage.NewPixmap(image.Rect(0, 0, 4, 4), oneimage.NRGBA8)
for y := 0; y < 4; y++ {
for x := 0; x < 4; x++ {
p.Set(x, y, color.NRGBA{R: uint8(60 * x), G: uint8(60 * y), B: 100, A: 255})
}
}
return oneimage.NewImage(p)
}
func main() {
m := oneimage.ColorMatrixSepia(1).Then(oneimage.ColorMatrixOpacity(0.5))
out, _ := oneimage.Apply(toneExampleImage(), oneimage.ApplyColorMatrix(m))
fmt.Println(m.IsIdentity(), out.At(0, 0))
}
Output: false {19 17 13 128}
type ColorModel ¶
type ColorModel uint8
ColorModel is what the channels of a pixel mean.
const ( // Gray has one channel. Gray ColorModel = iota + 1 // RGB has three channels: red, green, blue. RGB // CMYK has four channels. Ink amounts: 0 is no ink, the maximum is full ink. CMYK // Lab has three channels: L, a, b. Only Float32 holds it faithfully. Lab )
Color models. Indexed (palette) images are not a Pixmap model: they are carried as image.Paletted (see [DecodeOptions.KeepIndexed]).
func (ColorModel) MarshalText ¶
func (v ColorModel) MarshalText() ([]byte, error)
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (ColorModel) String ¶
func (m ColorModel) String() string
String returns the name of the ColorModel, spelled as its text form and Parse function read it.
func (*ColorModel) UnmarshalText ¶
func (v *ColorModel) UnmarshalText(text []byte) error
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type ColorOption ¶
type ColorOption interface {
// contains filtered or unexported methods
}
ColorOption adjusts a colour conversion. The defaults are relative colorimetric intent with black point compensation, as an editing application's "convert to profile" does.
func WithBlackPointCompensation ¶
func WithBlackPointCompensation(on bool) ColorOption
WithBlackPointCompensation turns black point compensation on or off (default on). It has no effect for AbsoluteColorimetric.
func WithIntent ¶
func WithIntent(i RenderingIntent) ColorOption
WithIntent selects the rendering intent (default RelativeColorimetric).
Example ¶
package main
import (
"fmt"
"image"
"recursiveai.org/go/oneimage"
)
func main() {
// Absolute colorimetric keeps a printing paper's white as it is measured:
// the paper of the generic CMYK profile is not pure white.
p := oneimage.NewPixmap(image.Rect(0, 0, 1, 1), oneimage.CMYK8) // all inks zero: bare paper
rel, _ := p.ConvertColor(nil, oneimage.SRGB())
abs, _ := p.ConvertColor(nil, oneimage.SRGB(), oneimage.WithIntent(oneimage.AbsoluteColorimetric))
fmt.Println(rel.Pix8, abs.Pix8[2] < rel.Pix8[2])
}
Output: [255 255 255] true
type ColorTransform ¶
type ColorTransform struct {
// contains filtered or unexported fields
}
ColorTransform converts pixels from one profile's colour space to another's. Build it once with NewColorTransform and reuse it; it is safe for concurrent use. It is the low-level entry point of colour management: codecs that hold CMYK data (JPEG, TIFF, PSD) use it directly.
func NewColorTransform ¶
func NewColorTransform(src, dst *Profile, opts ...ColorOption) (*ColorTransform, error)
NewColorTransform returns the conversion from src to dst for the given options. Transforms are cached by profile contents, intent and black point setting in a byte-bounded cache (see SetColorCacheBudget), so building the same transform again is cheap. A destination profile with no table for the requested direction (a CMYK profile with only A2B tags, say) fails with an error matching ErrUnsupported.
func (*ColorTransform) Convert ¶
func (t *ColorTransform) Convert(p *Pixmap) (*Pixmap, error)
Convert converts p, whose colour model must be that of the transform's source profile.
func (*ColorTransform) Destination ¶
func (t *ColorTransform) Destination() *Profile
Destination returns the profile the transform converts to.
func (*ColorTransform) Source ¶
func (t *ColorTransform) Source() *Profile
Source returns the profile the transform converts from.
type CommonOption ¶
type CommonOption interface {
DecodeOption
EncodeOption
OpOption
ColorOption
}
CommonOption is an option every kind of call accepts: it is a DecodeOption, an EncodeOption, an OpOption and a ColorOption at once. WithParallelism and WithLimits return one.
func FormatOption ¶
func FormatOption(v any) CommonOption
FormatOption wraps a value that only one format's decoder understands, so a format package can offer options of its own that work wherever options are taken: its option type embeds the result, which makes it a CommonOption, and the decoder finds v again in DecodeRequest.FormatOptions. A call that is not decoding ignores it.
func WithLimits ¶
func WithLimits(l Limits) CommonOption
WithLimits sets the resource limits of one call; the default is DefaultLimits. A decode checks sizes against them before allocating, an encode checks the image (frame count, size, total pixels, metadata) and hands them to a plug-in encoder, and an operation checks the size of the images it would create. It is accepted wherever WithParallelism is, except by colour conversion, which ignores it.
func WithParallelism ¶
func WithParallelism(n int) CommonOption
WithParallelism caps the goroutines one call uses at n: 1 keeps the work on the calling goroutine, 0 (the default) uses the process-wide setting (SetParallelism, by default runtime.GOMAXPROCS), and a negative value uses runtime.GOMAXPROCS whatever SetParallelism says. It is accepted by Decode, Open, Thumbnail and the other decoding calls, by Encode, by every operation that can use several goroutines (resize, filters, compositing, colour conversion) and by NewColorTransform. It changes speed only: pixels and encoded bytes are identical for every n. For a ColorTransform the value is fixed when the transform is built.
Example ¶
One call can be held to a number of goroutines; the result does not change.
package main
import (
"bytes"
"fmt"
"image"
"recursiveai.org/go/oneimage"
)
func main() {
var src bytes.Buffer
if err := oneimage.EncodePNG(&src, oneimage.NewPixmap(image.Rect(0, 0, 32, 32), oneimage.RGB8), nil); err != nil {
fmt.Println(err)
return
}
one, err := oneimage.DecodeBytes(src.Bytes(), oneimage.WithParallelism(1))
if err != nil {
fmt.Println(err)
return
}
many, err := oneimage.DecodeBytes(src.Bytes(), oneimage.WithParallelism(8))
if err != nil {
fmt.Println(err)
return
}
fmt.Println(one.Bounds() == many.Bounds())
}
Output: true
Example (Resize) ¶
Resizing on at most two goroutines.
package main
import (
"fmt"
"image"
"recursiveai.org/go/oneimage"
)
func main() {
img := oneimage.NewImage(oneimage.NewPixmap(image.Rect(0, 0, 400, 300), oneimage.RGB8))
out, err := img.Apply(oneimage.Resize(100, 75, oneimage.WithParallelism(2)))
if err != nil {
fmt.Println(err)
return
}
fmt.Println(out.Bounds().Dx(), out.Bounds().Dy())
}
Output: 100 75
type CurveInterpolation ¶
type CurveInterpolation uint8
CurveInterpolation says how Curves joins its points.
const ( CurveMonotone CurveInterpolation = iota CurveNatural )
The interpolations. CurveMonotone, the default, is a monotone cubic (Fritsch–Carlson) that never overshoots between points; CurveNatural is the natural cubic spline, which may.
func ParseCurveInterpolation ¶
func ParseCurveInterpolation(s string) (CurveInterpolation, error)
ParseCurveInterpolation reads "monotone" or "natural".
func (CurveInterpolation) MarshalText ¶
func (v CurveInterpolation) MarshalText() ([]byte, error)
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (CurveInterpolation) String ¶
func (c CurveInterpolation) String() string
String returns the name of the CurveInterpolation, spelled as its text form and Parse function read it.
func (*CurveInterpolation) UnmarshalText ¶
func (v *CurveInterpolation) UnmarshalText(text []byte) error
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type DecodeOption ¶
type DecodeOption interface {
// contains filtered or unexported methods
}
DecodeOption configures Decode, DecodeBytes, Identify and IdentifyBytes.
func WithAutoOrient ¶
func WithAutoOrient(v bool) DecodeOption
WithAutoOrient chooses whether the Exif orientation is applied to the pixels. Decode, Open and Thumbnail apply it by default; false returns the pixels as stored, with Metadata.Orientation untouched. With it applied, frames are upright, Width and Height are the upright size and Metadata.Orientation is 1. A Decode that asks for a WithRegion or WithScale keeps the stored orientation unless this is set to true, since the region is in stored coordinates.
func WithFormat ¶
func WithFormat(name string) DecodeOption
WithFormat forces a format by name instead of detecting it from the bytes.
func WithFrameLimit ¶
func WithFrameLimit(n int) DecodeOption
WithFrameLimit asks the decoder to stop after the first n frames (n > 0).
func WithKeepIndexed ¶
func WithKeepIndexed() DecodeOption
WithKeepIndexed asks for palette images as *image.Paletted.
func WithRegion ¶
func WithRegion(r image.Rectangle) DecodeOption
WithRegion decodes only r (full-size coordinates). A decoder that cannot decode a region directly decodes everything and crops.
Example (Tiff) ¶
package main
import (
"bytes"
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func main() {
src := image.NewGray(image.Rect(0, 0, 100, 100))
src.SetGray(40, 30, color.Gray{Y: 200})
var buf bytes.Buffer
if err := oneimage.EncodeTIFF(&buf, src, &oneimage.TIFFOptions{RowsPerStrip: 10}); err != nil {
panic(err)
}
img, err := oneimage.DecodeBytes(buf.Bytes(), oneimage.WithRegion(image.Rect(38, 28, 44, 34)))
if err != nil {
panic(err)
}
fmt.Println(img.Bounds().Size(), img.At(2, 2))
}
Output: (6,6) {200}
func WithRegistry ¶
func WithRegistry(r *Registry) DecodeOption
WithRegistry makes a call use the formats and default limits of r instead of the process-wide registry.
func WithRenderSize ¶
func WithRenderSize(w, h int) DecodeOption
WithRenderSize rasterises resolution-independent formats (SVG, metafiles) at w by h pixels; raster formats ignore it. Both sides zero (the default) is the picture's natural size; one zero side follows the natural aspect ratio; a negative side fails the decode with ErrOperation. FitRenderSize states the rule.
func WithScale ¶
func WithScale(n int) DecodeOption
WithScale decodes at 1/n size (n of 1, 2, 4 or 8). A format that cannot scale while decoding returns an ErrUnsupported error; resize the result instead.
Example ¶
package main
import (
"fmt"
"image"
"recursiveai.org/go/oneimage"
)
func main() {
src := image.NewGray(image.Rect(0, 0, 100, 60))
data, _ := oneimage.EncodeBytes(src, "jpeg", nil)
img, err := oneimage.DecodeBytes(data, oneimage.WithScale(4))
fmt.Println(err, img.Width(), img.Height())
}
Output: <nil> 25 15
func WithSourceCheck ¶
func WithSourceCheck(check func() error) DecodeOption
WithSourceCheck registers a function Open and Source call before they decode pixels after the first load. A non-nil result makes the read fail with a *SourceChangedError wrapping it. A caller whose bytes come from a file stats it when opening and has the check compare size and modification time; the library itself never touches files.
func WithValidate ¶
func WithValidate(v bool) DecodeOption
WithValidate makes Open decode every frame before returning, so damaged pixel data fails at Open instead of at the first read.
type DecodeRequest ¶
type DecodeRequest struct {
// Limits bounds allocation; the core passes it through [Limits.Resolved],
// so decoders can use it directly.
Limits Limits
// KeepIndexed asks for palette images as *image.Paletted frames instead of
// expanding them to a Pixmap. Decoders without palettes ignore it.
KeepIndexed bool
// FrameLimit, when positive, says the caller needs only the first n frames:
// a decoder may stop after them. Frames are composited, so the first n are
// the same either way. A decoder may ignore it and return all frames; the
// core drops the extra ones.
FrameLimit int
// Region, when not empty, asks for only that rectangle of the full-size
// image (full-size pixel coordinates, origin at the top left; pixels of
// the render when RenderSize is set). The result's bounds start at
// (0, 0). Sent only to decoders with CapRegion or CapRandomAccess; the
// core crops for the others.
Region image.Rectangle
// ScaleDenominator asks for 1/n size, n of 1, 2, 4 or 8 (0 means 1). Sent
// only to decoders with CapScale. When a Region is also set it is in
// full-size coordinates, and the result is the scaled region.
ScaleDenominator int
// RenderSize asks vector formats to rasterise at this size in pixels. Both
// sides zero means the format's own size; one zero side follows the
// natural aspect ratio ([FitRenderSize] resolves it, and every renderer
// should use it). The core rejects a negative side with [ErrOperation].
// Sent only to decoders with CapRenderSize.
RenderSize image.Point
// Parallelism is the most goroutines this decode may use (the call's
// [WithParallelism], resolved: at least 1). It changes speed only.
Parallelism int
// FormatOptions holds the values given with [FormatOption], in call order.
// A decoder takes the ones it knows and ignores the rest.
FormatOptions []any
// Context is cancelled when the caller gives up ([DecodeContext],
// [OpenContext], [ThumbnailContext]). The core sets it on every request it
// builds; a decoder that can take long (rasterising a vector format, a
// large animation) checks it at its natural steps and returns its Err. A
// nil Context means no cancellation.
Context context.Context
}
DecodeRequest is what a decoder is asked for. It is the low-level form of the DecodeOption values the happy-path functions take.
func DecodeRequestOf ¶
func DecodeRequestOf(opts ...DecodeOption) DecodeRequest
DecodeRequestOf returns the request the options describe, as the core would hand it to a decoder: limits resolved against their defaults, parallelism resolved to at least 1 (the call's WithParallelism, else the process-wide setting), and no context. It lets a format package that takes options of its own beside the common ones (WithLimits, WithParallelism) read the common ones.
type Decoder ¶
type Decoder interface {
// Capabilities reports the request hints the decoder honours.
Capabilities() Capabilities
// Identify reads the header facts without decoding pixels.
Identify(data []byte, lim Limits) (Info, error)
// Decode decodes every frame. Errors are [*FormatError], [*LimitError] or
// [*UnsupportedError]. Returned frames are composited, full-canvas
// pictures.
Decode(data []byte, req *DecodeRequest) (*Image, error)
}
Decoder reads one format. A decoder returns finished pictures (an *Image), not rows written into a caller's sink, so there is no row order to get wrong. Implementations are stateless and safe for concurrent use; they treat data as hostile: no panic, no hang, every allocation within req.Limits.
type Dither ¶
type Dither uint8
Dither selects how an encoder that reduces colours spreads the difference between an image and its palette. The error-diffusion kernels push each pixel's error onto the pixels after it, left to right and top to bottom; the ordered dithers add a fixed threshold pattern before choosing the nearest palette colour. All are deterministic.
const ( // DitherDefault is the zero value and means "the call's own default", // which differs by use: [DitherNone] for [Quantize] and Floyd–Steinberg // for [GIFOptions], [DitherToPalette] and [BinaryDither]. DitherDefault Dither = iota // DitherNone maps every pixel to its nearest palette colour. DitherNone DitherFloydSteinberg DitherAtkinson DitherBurkes DitherJarvisJudiceNinke DitherSierra2 DitherSierra3 DitherSierraLite DitherStevensonArce DitherStucki // DitherBayer2x2 to DitherBayer16x16 are ordered dithers with Bayer's // recursive threshold matrices. DitherBayer2x2 DitherBayer4x4 DitherBayer8x8 DitherBayer16x16 // DitherOrdered3x3 is an ordered dither with a 3 by 3 matrix. DitherOrdered3x3 )
Dithers.
func ParseDither ¶
ParseDither reads a dither name as Dither.String writes it.
func (Dither) MarshalText ¶
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (Dither) String ¶
String returns the dither's name as the options of other tools spell it ("floyd-steinberg", "bayer8x8", ...).
func (*Dither) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type DrawOption ¶
type DrawOption func(*drawOpts)
DrawOption adjusts a drawing call.
func WithClipPath ¶
func WithClipPath(clip Path, rule FillRule) DrawOption
WithClipPath limits a fill or stroke to the inside of clip under rule: the clip's coverage is multiplied into the shape's, so only pixels inside both change and the clip edge is anti-aliased like any other. The clip is in pixel coordinates; WithTransform does not move it.
Example ¶
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func must[T any](v T, err error) T {
if err != nil {
panic(err)
}
return v
}
func main() {
pm := oneimage.NewPixmap(image.Rect(0, 0, 4, 1), oneimage.Gray8)
clip := must(oneimage.RectPath(1, 0, 2, 1))
err := pm.FillPath(oneimage.SolidBrush(color.NRGBA{255, 255, 255, 255}), must(oneimage.RectPath(0, 0, 4, 1)),
oneimage.WithClipPath(clip, oneimage.FillNonZero))
if err != nil {
panic(err)
}
fmt.Println(pm.Pix8)
}
Output: [0 255 255 0]
func WithDrawBlend ¶
func WithDrawBlend(m BlendMode) DrawOption
WithDrawBlend sets how the paint's colour combines with the colour under it (default BlendNormal); a mode outside the defined ones makes the call fail with ErrOperation.
Example ¶
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func main() {
pm := oneimage.NewPixmap(image.Rect(0, 0, 1, 1), oneimage.NRGBA8)
pm.Set(0, 0, color.NRGBA{128, 128, 128, 255})
if err := pm.FillColor(color.NRGBA{255, 0, 0, 255}, oneimage.WithDrawBlend(oneimage.BlendMultiply)); err != nil {
panic(err)
}
fmt.Println(pm.Pix8[0:4])
}
Output: [128 0 0 255]
func WithDrawComposition ¶
func WithDrawComposition(c AlphaComposition) DrawOption
WithDrawComposition sets the Porter-Duff operator (default CompSrcOver). On a pixmap without alpha only the operators that keep it opaque are allowed (src-over, src-atop, dest, dest-over).
func WithDrawOpacity ¶
func WithDrawOpacity(v float64) DrawOption
WithDrawOpacity multiplies the alpha of the paint, 0..1 (default 1).
func WithFillRule ¶
func WithFillRule(r FillRule) DrawOption
WithFillRule sets the rule of a fill (default FillNonZero); strokes are always non-zero.
func WithFlatness ¶
func WithFlatness(tolerance float64) DrawOption
WithFlatness sets the flattening tolerance in pixels (default DefaultFlatnessTolerance); it must be positive.
func WithLinearLight ¶
func WithLinearLight() DrawOption
WithLinearLight blends in linear light instead of the stored (encoded) values: brush colours and pixels are converted with the sRGB curve, mixed, and converted back. Gradient colours then interpolate in linear light too.
Example ¶
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func main() {
pm := oneimage.NewPixmap(image.Rect(0, 0, 1, 1), oneimage.NRGBA8)
pm.Set(0, 0, color.NRGBA{0, 0, 0, 255})
white := color.NRGBA{255, 255, 255, 255}
if err := pm.FillColor(white, oneimage.WithDrawOpacity(0.5), oneimage.WithLinearLight()); err != nil {
panic(err)
}
fmt.Println(pm.Pix8[0] > 180) // half of linear light is sRGB 188, not 128
}
Output: true
func WithTransform ¶
func WithTransform(m Matrix3x2) DrawOption
WithTransform maps the path before filling or stroking it. It moves only the path: a brush stays in the pixel grid. A stroke's width is scaled by it (SVG). A singular or non-finite matrix is refused.
func WithoutAntialiasing ¶
func WithoutAntialiasing() DrawOption
WithoutAntialiasing covers a pixel when its centre is inside the shape instead of by the exact area under it.
type Edge ¶
type Edge uint8
Edge says what a sample taken outside the image sees: a transform's source beyond the border, or the rows added by Pad.
const ( // EdgeConstant uses the background colour. It is the default. EdgeConstant Edge = iota // EdgeClamp repeats the border pixel. EdgeClamp // EdgeMirror reflects the image, repeating the border pixel once (abc // reads cba|abc|cba). EdgeMirror // EdgeWrap tiles the image. EdgeWrap )
The edge modes.
func (Edge) MarshalText ¶
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (Edge) String ¶
String returns the name of the Edge, spelled as its text form and Parse function read it.
func (*Edge) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type EdgeDetector ¶
type EdgeDetector uint8
EdgeDetector selects the kernel of DetectEdges.
const ( EdgeSobel EdgeDetector = iota EdgePrewitt EdgeScharr EdgeRobertsCross EdgeKayyali EdgeLaplacian3x3 EdgeLaplacian5x5 EdgeLaplacianOfGaussian EdgeKirsch EdgeRobinson )
The detectors. The gradient kinds (Sobel, Prewitt, Scharr, Roberts cross, Kayyali) combine two kernels as the square root of the sum of squares; the Laplacians use one kernel; Kirsch and Robinson take the largest response of eight compass kernels.
func ParseEdgeDetector ¶
func ParseEdgeDetector(s string) (EdgeDetector, error)
ParseEdgeDetector reads a detector name as String writes it.
func (EdgeDetector) MarshalText ¶
func (v EdgeDetector) MarshalText() ([]byte, error)
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (EdgeDetector) String ¶
func (d EdgeDetector) String() string
String returns the name of the EdgeDetector, spelled as its text form and Parse function read it.
func (*EdgeDetector) UnmarshalText ¶
func (v *EdgeDetector) UnmarshalText(text []byte) error
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type EncodeOption ¶
type EncodeOption interface {
// contains filtered or unexported methods
}
EncodeOption configures Encode and EncodeBytes.
func WithEncodeRegistry ¶
func WithEncodeRegistry(r *Registry) EncodeOption
WithEncodeRegistry looks the format up in r instead of the process-wide registry.
type EncodeRequest ¶
type EncodeRequest struct {
// Limits are the call's limits with defaults filled in; the image has
// already been checked against them.
Limits Limits
// Parallelism is the most goroutines this encode may use (the call's
// [WithParallelism], resolved: at least 1). It changes speed only.
Parallelism int
// Context is the call's context ([EncodeContext]); never nil. Writes to
// the destination already stop when it is cancelled; an encoder with long
// stretches between writes checks it as well.
Context context.Context
}
EncodeRequest is what an encoder is told about the call it serves. It is the last argument of Encoder.Encode; the core always passes one, and code that calls an encoder directly may pass nil for defaults.
type Encoder ¶
type Encoder interface {
// Encode writes img. opts is nil for defaults, or a pointer to the
// format's options type (for PNG, *[PNGOptions]); any other type is an
// [ErrOperation]. req carries the call's limits, parallelism and context;
// a nil req means the default limits, one goroutine per core and no
// cancellation. The output depends only on img and opts, never on req.
Encode(w io.Writer, img *Image, opts any, req *EncodeRequest) error
}
Encoder writes one format. An encoder that restricts its input (one frame, some pixel formats) also implements InfoEncoder.
Every built-in encoder documents its options type on the format's entry point (PNGOptions, JPEGOptions, GIFOptions, WebPOptions, TIFFOptions, BMPOptions, ICOOptions); Format.NewOptions returns a fresh zero value of it for generic callers.
type EncoderInfo ¶
type EncoderInfo struct {
// SingleFrame says the encoder writes one picture. [Encode] then passes
// only the first frame, with a loop count of zero.
SingleFrame bool
// PixelFormats lists the formats the encoder reads, most preferred last
// among equals. [Encode] converts each frame to the best of them (see
// [BestFormat]) before calling the encoder. Empty means every format.
PixelFormats []PixelFormat
}
EncoderInfo describes what an Encoder accepts, so the core can prepare the image before the encoder sees it. An encoder reports it by implementing InfoEncoder; the zero value (what an encoder without the method gets) means any number of frames in any pixel format.
type EqualizeMethod ¶
type EqualizeMethod uint8
EqualizeMethod selects the algorithm of HistogramEqualization.
const ( EqualizeGlobal EqualizeMethod = iota EqualizeAdaptiveTile EqualizeAdaptiveSlidingWindow )
The methods. EqualizeGlobal uses one histogram for the whole image. EqualizeAdaptiveTile builds a histogram per tile and interpolates between the tiles' mappings. EqualizeAdaptiveSlidingWindow uses a window around every pixel.
func ParseEqualizeMethod ¶
func ParseEqualizeMethod(s string) (EqualizeMethod, error)
ParseEqualizeMethod reads a method name as String writes it.
func (EqualizeMethod) MarshalText ¶
func (v EqualizeMethod) MarshalText() ([]byte, error)
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (EqualizeMethod) String ¶
func (m EqualizeMethod) String() string
String returns the name of the EqualizeMethod, spelled as its text form and Parse function read it.
func (*EqualizeMethod) UnmarshalText ¶
func (v *EqualizeMethod) UnmarshalText(text []byte) error
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type ExifFields ¶
type ExifFields struct {
// Orientation is 1 to 8, or 0 when the tag is absent or not a SHORT in
// that range.
Orientation int
// PixelWidth and PixelHeight come from PixelXDimension and PixelYDimension
// in the Exif IFD, falling back to ImageWidth and ImageLength of the first
// IFD; 0 when absent.
PixelWidth, PixelHeight int
// Make, Model and Software are the ASCII tags of the first IFD, up to the
// first NUL, with trailing spaces trimmed.
Make, Model, Software string
// CaptureTime is DateTimeOriginal, else DateTimeDigitized, else DateTime,
// as a wall-clock time with no zone (reported in UTC); zero when absent
// or unparsable.
CaptureTime time.Time
// GPS is the position, nil unless latitude and longitude are both present
// and valid.
GPS *GPS
}
ExifFields are the commonly used tags of an Exif block. A tag that is missing, has an unexpected type or holds an invalid value is left at its zero value, so a damaged tag never hides the others.
func ParseExif ¶
func ParseExif(exif []byte) (ExifFields, error)
ParseExif reads the common tags of an Exif block: a TIFF stream as found in Metadata.Exif, with or without a leading "Exif\0\0". Both byte orders are read. Only the first IFD, the Exif IFD and the GPS IFD are visited, each once, so a block whose IFD chain loops cannot hang the reader. A block that is not a TIFF stream, or whose first IFD lies outside it, is a FormatError; damaged individual tags are skipped (see ExifFields).
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/oneimage"
)
func main() {
// A little-endian block with one entry: Orientation (tag 0x0112) = 6.
exif := []byte("II*\x00\x08\x00\x00\x00\x01\x00\x12\x01\x03\x00\x01\x00\x00\x00\x06\x00\x00\x00\x00\x00")
f, err := oneimage.ParseExif(exif)
fmt.Println(f.Orientation, err)
}
Output: 6 <nil>
type FillRule ¶
type FillRule uint8
FillRule decides which points a path with overlapping or nested figures encloses.
const ( // FillNonZero encloses points whose winding number is not zero (the // default everywhere). FillNonZero FillRule = iota // FillEvenOdd encloses points a ray from outside crosses an odd number of // times. FillEvenOdd )
Fill rules.
func (FillRule) MarshalText ¶
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (*FillRule) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type Filter ¶
type Filter uint8
Filter selects a resampling kernel.
const ( FilterAuto Filter = iota FilterNearest FilterBox FilterBilinear FilterCatmullRom FilterMitchell FilterLanczos2 FilterLanczos3 FilterLanczos5 FilterLanczos8 FilterHermite FilterRobidoux FilterRobidouxSharp FilterSpline FilterWelch )
The resampling filters. FilterAuto, the zero value, picks per axis: Lanczos3 where the axis shrinks and Catmull-Rom otherwise. FilterBilinear is the triangle filter.
func ParseFilter ¶
ParseFilter reads a filter name as String writes it; "bicubic" and "triangle" are accepted as aliases of Catmull-Rom and bilinear. Names are compared ignoring ASCII case.
func (Filter) MarshalText ¶
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (Filter) String ¶
String returns the name of the Filter, spelled as its text form and Parse function read it.
func (*Filter) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type Fit ¶
type Fit uint8
Fit says how Resize fits an image into a width-by-height box.
const ( // FitContain scales to the largest size inside the box, keeping the // aspect ratio. The result can be smaller than the box in one dimension. FitContain Fit = iota // FitCover scales to the smallest size covering the box and crops the // overflow (placed by the anchor): the result is exactly the box, or // smaller when upscaling is off and the image is smaller. FitCover // FitStretch scales each axis to the box, ignoring the aspect ratio. FitStretch // FitPad is FitContain on a canvas of exactly the box size, filled with // the background around the image. FitPad // FitBoxPad is FitPad, except an image that already fits in the box is // not scaled, only placed. FitBoxPad // FitMin scales so the result is at least as large as the box in both // dimensions without upscaling beyond the original: an image that already // reaches the box in either dimension keeps its size. FitMin FitMax = FitContain FitCrop = FitCover )
The fit modes. The aliases FitMax (contain) and FitCrop (cover) name the same behaviour.
func (Fit) MarshalText ¶
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (Fit) String ¶
String returns the name of the Fit, spelled as its text form and Parse function read it.
func (*Fit) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type Format ¶
type Format struct {
// Name is the lower-case format name: "png", "jpeg", ...
Name string
// MIMEType is the media type, such as "image/png".
MIMEType string
// Extensions are lower-case file extensions with the dot, most common first.
Extensions []string
// Sniff reports whether head, the first bytes of a file (up to
// [SniffLength]), look like this format. It must be cheap and must not
// accept another format's signature.
Sniff func(head []byte) bool
// Decoder and Encoder are optional: a format may only read or only write.
Decoder Decoder
// Encoder writes the format; nil for a format that is only read.
Encoder Encoder
// NewOptions, when set, returns a new zero options value for the encoder,
// the pointer type [Encoder.Encode] accepts (a *[PNGOptions] for "png"). It
// lets generic code, such as a command-line tool or a web handler, fill
// in a format's options by field name without knowing the type. Nil means
// the format takes no options.
NewOptions func() any
}
Format describes a registered image format. Packages outside the core (SVG, metafiles, and so on) register theirs the same way from init.
func Detect ¶
Detect returns the format whose signature head carries, trying the registered formats in order. head should be the first SniffLength bytes of the file (fewer if the file is shorter).
func FormatForExtension ¶
FormatForExtension finds a registered format by file extension, compared ignoring ASCII case. ext may be the extension with or without its dot ("png", ".png") or a file name or path ("dir/photo.JPG"), whose extension is the part after the last dot of the last path element.
func Formats ¶
func Formats() []Format
Formats returns the registered formats in registration order.
func LookupFormat ¶
LookupFormat finds a registered format by name, ignoring ASCII case. A name that matches no format is tried as a file extension, so "jpg" and "tif" find "jpeg" and "tiff" (see FormatForExtension); a format's own name wins.
Example ¶
LookupFormat finds a format by name or by file extension.
package main
import (
"fmt"
"recursiveai.org/go/oneimage"
)
func main() {
f, ok := oneimage.LookupFormat("jpg")
fmt.Println(f.Name, ok)
}
Output: jpeg true
type FormatError ¶
type FormatError struct {
// Format is the format being read, or empty when none was detected.
Format string
// Msg says what is wrong, in plain words.
Msg string
// Offset is the byte position in the data where the problem was found
// (for PNG, the start of the offending chunk), or 0 when the decoder
// does not know. It is a hint for diagnostics, not a promise.
Offset int64
// Err is an underlying error, if any.
Err error
}
FormatError describes invalid image data. It matches ErrFormat.
func (*FormatError) Error ¶
func (e *FormatError) Error() string
Error describes the invalid data, with its format and offset when known.
func (*FormatError) Unwrap ¶
func (e *FormatError) Unwrap() []error
Unwrap lets errors.Is match both ErrFormat and the underlying error.
type Frame ¶
type Frame struct {
// Image holds the pixels: a *Pixmap, or an *image.Paletted when a decoder
// was asked to keep indexed images ([DecodeRequest.KeepIndexed]).
Image image.Image
// Delay is how long to show the frame; zero for a still image.
Delay time.Duration
}
Frame is one image of a still or animated file: a complete raster of the canvas size, with the time to show it.
Decoders return animated formats' frames already composited onto the canvas (after the format's disposal and blend rules), so every frame is a full picture and frames can be used independently.
func (Frame) Pixmap ¶
Pixmap returns the frame's pixels as a *Pixmap. A *Pixmap frame is returned as is (shared, not copied); an *image.Paletted or any other image.Image is converted as FromImage does, so the common case needs no type assertion. The result is never nil when the error is nil; a frame without an Image is an ErrOperation.
Example ¶
A Frame hands out its pixels as a Pixmap whatever image type it holds.
package main
import (
"fmt"
"image"
"recursiveai.org/go/oneimage"
)
func main() {
f := oneimage.Frame{Image: image.NewGray(image.Rect(0, 0, 3, 2))}
pm, err := f.Pixmap()
fmt.Println(err, pm.Rect.Dx(), pm.Rect.Dy())
}
Output: <nil> 3 2
type FrameInfo ¶
type FrameInfo struct {
// Width and Height are the size of the frame's picture: the canvas for
// animations (frames are composited) and the entry's own size for ICO and
// multi-page TIFF.
Width, Height int
// Delay is how long the frame shows; zero for a still image.
Delay time.Duration
}
FrameInfo is what a file declares about one frame without decoding it.
type GIFDisposal ¶
type GIFDisposal uint8
GIFDisposal says what happens to a frame's rectangle before the next frame is drawn (GIF89a section 23).
const ( // GIFDisposalNone (0) and GIFDisposalKeep (1): leave the frame in place. GIFDisposalNone GIFDisposal = iota GIFDisposalKeep // GIFDisposalBackground clears the frame's rectangle to transparent. GIFDisposalBackground // GIFDisposalPrevious restores the canvas as it was before the frame. GIFDisposalPrevious )
Disposal methods. Values 4 to 7 are reserved by the specification; decoders treat them as GIFDisposalNone.
func (GIFDisposal) MarshalText ¶
func (v GIFDisposal) MarshalText() ([]byte, error)
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (GIFDisposal) String ¶
func (v GIFDisposal) String() string
String returns the lower-case name, or GIFDisposal(n) for an unknown value.
func (*GIFDisposal) UnmarshalText ¶
func (v *GIFDisposal) UnmarshalText(text []byte) error
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type GIFFrameInfo ¶
type GIFFrameInfo struct {
// Bounds is the frame's rectangle on the screen as stored, which may extend
// past it; decoding clips it.
Bounds image.Rectangle
// Interlaced reports the four-pass row order.
Interlaced bool
// LocalPalette reports a colour table of the frame's own.
LocalPalette bool
// Disposal is the frame's disposal method.
Disposal GIFDisposal
// TransparentIndex is the palette index that is not drawn, or -1.
TransparentIndex int
}
GIFFrameInfo is what a GIF file states about one frame.
type GIFInfo ¶
type GIFInfo struct {
// Version is "87a" or "89a".
Version string
// ScreenWidth and ScreenHeight are the logical screen as stored; both are
// 0 when the file leaves it to the frames (the canvas is then their bounding
// box).
ScreenWidth, ScreenHeight int
// BackgroundIndex is the stored background colour index.
BackgroundIndex int
// GlobalPalette reports a global colour table.
GlobalPalette bool
// Frames describes each frame in file order.
Frames []GIFFrameInfo
}
GIFInfo holds the facts a GIF file states about itself. Decoding fills it in Image.Details and Info.Details. The background colour index is reported and never painted: like browsers, the decoder starts from a transparent screen and clears to transparent.
type GIFOptions ¶
type GIFOptions struct {
// MaxColors bounds the palette of a frame, 2 to 256; 0 means 256. A
// transparent entry counts toward it.
MaxColors int
// Dither spreads the error of a reduction to MaxColors or to a fixed
// palette; the default is Floyd–Steinberg. A frame that fits its palette
// exactly is never dithered.
Dither Dither
// Quantizer chooses the palette of a frame that has more colours than fit;
// the default is Wu's. The fixed-palette quantizers always use their own
// palette, which must fit MaxColors.
Quantizer Quantizer
// FrameDifferencing stores each frame after the first as the smallest
// rectangle that changes the screen. The decoded animation is the same;
// the file is smaller. A frame that changes nothing becomes a one-pixel
// frame so that it keeps its delay.
FrameDifferencing bool
// StripMetadata leaves out the ICC profile and XMP packet that would
// otherwise be carried over from the image.
StripMetadata bool
}
GIFOptions configures the GIF encoder. The zero value is the default.
Example ¶
package main
import (
"bytes"
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func main() {
// 1000 colours squeezed into 16 with an ordered dither and Wu's quantizer.
m := image.NewNRGBA(image.Rect(0, 0, 40, 25))
for y := 0; y < 25; y++ {
for x := 0; x < 40; x++ {
m.SetNRGBA(x, y, color.NRGBA{R: uint8(x * 6), G: uint8(y * 10), B: uint8(x + y), A: 255})
}
}
var buf bytes.Buffer
opts := &oneimage.GIFOptions{MaxColors: 16, Dither: oneimage.DitherBayer4x4, Quantizer: oneimage.QuantizerWu}
if err := oneimage.EncodeGIF(&buf, m, opts); err != nil {
panic(err)
}
info, _ := oneimage.IdentifyBytes(buf.Bytes())
fmt.Println(info.Width, info.Height, info.NumFrames, opts.Dither)
}
Output: 40 25 1 bayer4x4
type GPS ¶
type GPS struct {
// Latitude and Longitude are in decimal degrees, south and west negative.
Latitude, Longitude float64
// Altitude is in metres above sea level, negative below; it is meaningful
// only when HasAltitude is set.
Altitude float64
// HasAltitude says Altitude is present in the Exif block.
HasAltitude bool
}
GPS is a position read from the GPS IFD of an Exif block.
type HatchStyle ¶
type HatchStyle uint8
HatchStyle is one of the built-in 4 by 4 cell patterns.
const ( HatchHorizontal HatchStyle = iota HatchVertical HatchForwardDiagonal HatchBackwardDiagonal HatchPercent10 HatchPercent20 HatchMin )
Hatch styles.
func (HatchStyle) MarshalText ¶
func (v HatchStyle) MarshalText() ([]byte, error)
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (HatchStyle) String ¶
func (v HatchStyle) String() string
String returns the lower-case name, or HatchStyle(n) for an unknown value.
func (*HatchStyle) UnmarshalText ¶
func (v *HatchStyle) UnmarshalText(text []byte) error
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type Histogram ¶
type Histogram struct {
// Bins is the number of bins per channel.
Bins int
// PixelCount is the number of pixels counted (all of them, or the ones
// with alpha above 0 under [SkipTransparent]).
PixelCount int
// Channels holds one slice of Bins counts per channel: red, green, blue
// (or the single gray channel), then alpha when the image has it.
Channels [][]uint64
}
Histogram is the count of samples per bin for each channel of an image.
type ICOEntry ¶
type ICOEntry struct {
// Width and Height are the directory's sizes (256 where the file stores 0).
Width, Height int
// BitCount is the stored bits per pixel (0 when the file leaves it out).
BitCount int
// HotspotX and HotspotY are a cursor's hot spot; 0 for icons.
HotspotX, HotspotY int
// PNG reports that the entry is a PNG file rather than a bitmap.
PNG bool
}
ICOEntry is one directory entry of an icon or cursor file.
type ICOInfo ¶
type ICOInfo struct {
// Cursor reports a cursor (.cur) file rather than an icon.
Cursor bool
// Entries lists the directory in file order.
Entries []ICOEntry
}
ICOInfo holds the facts an icon file states about itself.
type ICOOptions ¶
type ICOOptions struct {
// PNGThreshold is the size from which an entry is stored as a PNG instead
// of a bitmap: an entry whose larger side is at least this. 0 means 256,
// so only 256-pixel entries are PNGs.
PNGThreshold int
}
ICOOptions configures the ICO encoder. The zero value is the default.
type Image ¶
type Image struct {
// Format is the name of the format the image came from ("png", ...), or
// empty for an image built in memory.
Format string
// Frames holds at least one frame in display order. Frames may differ in
// size: the pages of a PDF or a multi-page TIFF are frames of their own
// sizes, while the frames of an animation share the canvas. [Image.Bounds],
// [Image.At] and [Image.ColorModel] describe the first frame only.
Frames []Frame
// LoopCount is the number of times an animation plays; 0 means forever.
// A still image has 0.
LoopCount int
// Metadata carries the embedded profile and metadata blobs.
Metadata Metadata
// Details holds the source format's own facts: a *[PNGInfo] for PNG. It
// is nil for images built in memory. Encoders use it to carry such facts
// (for PNG, the colour chunks) over to the output.
Details any
// contains filtered or unexported fields
}
Image is a decoded (or to-be-encoded) picture: one or more frames, metadata, and the facts of the source format.
*Image implements image.Image by delegating to its first frame (its size is the first frame's even when later frames differ), so a still image can be passed straight to code that takes an image.Image.
The fields are plain values: a caller may build an Image from them and edit them. Operations (Apply) never change their input, but they share the frames they leave alone with their result, so writing into a frame's pixels changes every Image that shares it; copy first (see Pixmap.Clone) when that matters.
func Apply ¶
Apply runs ops on img in order and returns the result. An empty list, or a list of identity operations, returns img itself. Errors carry the failing operation's name and match ErrOperation, ErrLimit or ErrUnsupported.
Example ¶
Operations are values that apply to every frame of an image; Apply runs a chain of them.
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func opExampleImage(w, h int) *oneimage.Image {
p := oneimage.NewPixmap(image.Rect(0, 0, w, h), oneimage.NRGBA8)
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
p.Set(x, y, color.NRGBA{R: uint8(x * 255 / w), G: uint8(y * 255 / h), B: 128, A: 255})
}
}
return oneimage.NewImage(p)
}
func main() {
img := opExampleImage(64, 48)
out, err := oneimage.Apply(img,
oneimage.Resize(32, 32), // contain: 32x24
oneimage.Rotate(90), // exact quarter turn: 24x32
oneimage.Pad(4, 4, 4, 4), // transparent border
oneimage.Crop(image.Rect(0, 0, 20, 20)))
if err != nil {
panic(err)
}
fmt.Println(out.Width(), out.Height())
}
Output: 20 20
func ApplyContext ¶
ApplyContext is Apply that stops when ctx is cancelled: it checks before every operation, between the frames of an animation and between blocks of rows in the long kernels (resampling, filters, compositing, colour conversion), and returns ctx.Err() (not wrapped with an operation name).
Example ¶
package main
import (
"context"
"fmt"
"image"
"recursiveai.org/go/oneimage"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
cancel()
img := oneimage.NewImage(oneimage.NewPixmap(image.Rect(0, 0, 8, 8), oneimage.NRGBA8))
_, err := oneimage.ApplyContext(ctx, img, oneimage.Invert())
fmt.Println(err)
}
Output: context canceled
func CombineChannels ¶
CombineChannels is the inverse of SplitChannels: one to four gray images of the same size and sample type become gray, gray with alpha, RGB or RGBA.
func Decode ¶
func Decode(r io.Reader, opts ...DecodeOption) (*Image, error)
Decode reads an image from r in any registered format, detected from its first bytes. The whole input is read into memory first, up to Limits.MaxInputBytes. Animated images give every frame.
Pixels come upright, as from Open and Thumbnail: a stored Exif orientation is applied and Metadata.Orientation reads 1 afterwards. WithAutoOrient(false) returns the pixels as stored. A call that also asks for a WithRegion or WithScale works in the stored frame, so it keeps the stored orientation unless WithAutoOrient(true) is given.
Example ¶
package main
import (
"bytes"
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func main() {
src := image.NewNRGBA(image.Rect(0, 0, 4, 2))
src.SetNRGBA(1, 1, color.NRGBA{R: 200, G: 100, B: 50, A: 255})
var buf bytes.Buffer
if err := oneimage.EncodePNG(&buf, src, nil); err != nil {
panic(err)
}
img, err := oneimage.Decode(&buf)
if err != nil {
panic(err)
}
fmt.Println(img.Format, img.Width(), img.Height(), len(img.Frames))
fmt.Println(img.At(1, 1))
}
Output: png 4 2 1 {200 100 50 255}
func DecodeBytes ¶
func DecodeBytes(data []byte, opts ...DecodeOption) (*Image, error)
DecodeBytes is Decode for data already in memory; the decoder reads it without copying.
func DecodeBytesContext ¶
DecodeBytesContext is DecodeBytes with the cancellation of DecodeContext.
func DecodeContext ¶
DecodeContext is Decode that stops when ctx is cancelled or its deadline passes, returning ctx.Err(). The context is checked while the input is read and is passed to the decoder as DecodeRequest.Context, so formats that render (SVG, metafiles) or layer-composite (PSD) stop within a step of the cancellation; a decoder that cannot be interrupted finishes its frame first.
Example ¶
A context stops a decode; the same options work with every call.
package main
import (
"context"
"fmt"
"image"
"recursiveai.org/go/oneimage"
)
func main() {
var buf []byte
{
src := oneimage.NewPixmap(image.Rect(0, 0, 8, 8), oneimage.NRGBA8)
b, err := oneimage.EncodeBytes(src, "png", nil)
if err != nil {
fmt.Println(err)
return
}
buf = b
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err := oneimage.DecodeBytesContext(ctx, buf, oneimage.WithLimits(oneimage.DefaultLimits()), oneimage.WithParallelism(1))
fmt.Println(err)
}
Output: context canceled
func NewAnimation ¶
NewAnimation builds an image from frames. loopCount is the number of times it plays, 0 for forever. Every frame must have pixels and the same bounds size as the first; the frames are used as given (not copied). A single frame makes a still image. The result has no format, metadata or details; set Metadata on it to carry a profile or Exif.
Encoders that store animations (GIF, APNG, WebP, TIFF pages) write the frames with their delays and the loop count; a frame's Delay is shown for that long, and encoders round it to what the format can store.
Example ¶
package main
import (
"fmt"
"image"
"image/color"
"time"
"recursiveai.org/go/oneimage"
)
func main() {
red := oneimage.NewPixmap(image.Rect(0, 0, 4, 4), oneimage.NRGBA8)
red.FillColor(color.NRGBA{R: 255, A: 255})
blue := oneimage.NewPixmap(image.Rect(0, 0, 4, 4), oneimage.NRGBA8)
blue.FillColor(color.NRGBA{B: 255, A: 255})
anim, _ := oneimage.NewAnimation(2,
oneimage.Frame{Image: red, Delay: 100 * time.Millisecond},
oneimage.Frame{Image: blue, Delay: 300 * time.Millisecond})
data, _ := oneimage.EncodeBytes(anim, "gif", nil)
back, _ := oneimage.DecodeBytes(data)
fmt.Println(len(back.Frames), back.LoopCount, back.Duration())
}
Output: 2 2 400ms
func NewImage ¶
NewImage returns a single-frame Image around img. If img is already an *Image it is returned as is, and a nil img gives nil, as FromImage does.
func SplitChannels ¶
SplitChannels returns the channels of the first frame as gray images of the same size and sample type: red, green, blue (or the single gray channel), then alpha when there is one. Colour is the straight (not premultiplied) value.
Example ¶
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func toneExampleImage() *oneimage.Image {
p := oneimage.NewPixmap(image.Rect(0, 0, 4, 4), oneimage.NRGBA8)
for y := 0; y < 4; y++ {
for x := 0; x < 4; x++ {
p.Set(x, y, color.NRGBA{R: uint8(60 * x), G: uint8(60 * y), B: 100, A: 255})
}
}
return oneimage.NewImage(p)
}
func main() {
parts, _ := oneimage.SplitChannels(toneExampleImage())
back, _ := oneimage.CombineChannels(parts...)
fmt.Println(len(parts), back.At(3, 3))
}
Output: 4 {180 180 100 255}
func Thumbnail ¶
Thumbnail reads an image from r and returns it scaled to fit inside a width-by-height box, the way Resize with FitContain does but never enlarging (unless WithUpscale(true) is passed), turned upright by its Exif orientation, with the Exif, XMP and IPTC blocks and text entries dropped (they can carry location and other private data; WithKeepMetadata keeps them) and the ICC profile kept. All frames of an animation are scaled.
A format whose decoder can decode at a reduced size (JPEG's DCT scaling) is asked to, so a large photograph is never fully decoded; the result then differs from decode-then-resize by rounding only. Options read: WithFilter, WithFit, WithAnchor, WithUpscale, WithLinear, WithBackground and WithLimits, whose limits also bound the decode.
Example ¶
Thumbnail decodes, turns the image upright, scales it into the box without enlarging, and keeps only the colour profile of the metadata.
package main
import (
"bytes"
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func opExampleImage(w, h int) *oneimage.Image {
p := oneimage.NewPixmap(image.Rect(0, 0, w, h), oneimage.NRGBA8)
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
p.Set(x, y, color.NRGBA{R: uint8(x * 255 / w), G: uint8(y * 255 / h), B: 128, A: 255})
}
}
return oneimage.NewImage(p)
}
func main() {
var buf bytes.Buffer
if err := oneimage.EncodePNG(&buf, opExampleImage(400, 300), nil); err != nil {
panic(err)
}
th, err := oneimage.Thumbnail(&buf, 100, 100)
if err != nil {
panic(err)
}
fmt.Println(th.Width(), th.Height())
}
Output: 100 75
func ThumbnailBytes ¶
ThumbnailBytes is Thumbnail for an image held in memory.
Example ¶
package main
import (
"fmt"
"image"
"recursiveai.org/go/oneimage"
)
func gradientPNG(w, h int) []byte {
pm := oneimage.NewPixmap(image.Rect(0, 0, w, h), oneimage.RGB8)
for y := 0; y < h; y++ {
row := pm.Row8(y)
for x := 0; x < w; x++ {
row[3*x], row[3*x+1], row[3*x+2] = byte(x), byte(y), 128
}
}
data, _ := oneimage.EncodeBytes(pm, "png", nil)
return data
}
func main() {
th, _ := oneimage.ThumbnailBytes(gradientPNG(200, 100), 50, 50)
fmt.Println(th.Bounds().Size())
}
Output: (50,25)
func ThumbnailBytesContext ¶
func ThumbnailBytesContext(ctx context.Context, data []byte, width, height int, opts ...OpOption) (*Image, error)
ThumbnailBytesContext is ThumbnailBytes with the cancellation of ThumbnailContext.
func ThumbnailContext ¶
func ThumbnailContext(ctx context.Context, r io.Reader, width, height int, opts ...OpOption) (*Image, error)
ThumbnailContext is Thumbnail that stops when ctx is cancelled or its deadline passes, returning ctx.Err(). The context is checked while the input is read, passed to the decoder (DecodeRequest.Context) and checked between the frames and blocks of rows of the scaling.
func ThumbnailImage ¶
ThumbnailImage scales a decoded image to fit inside a width-by-height box with the same rules as Thumbnail (never enlarging unless WithUpscale(true), upright, Exif/XMP/IPTC and text dropped unless WithKeepMetadata, ICC profile kept). The input is not changed.
func ThumbnailImageContext ¶
func ThumbnailImageContext(ctx context.Context, img image.Image, width, height int, opts ...OpOption) (*Image, error)
ThumbnailImageContext is ThumbnailImage that stops when ctx is cancelled, as ApplyContext does.
func ToSRGB ¶
ToSRGB converts the image to sRGB (relative colorimetric, black point compensation on) and embeds the compact sRGB profile. It is the happy path for getting predictable colours out of any input.
func (*Image) ApplyContext ¶
ApplyContext runs ops on m; see ApplyContext.
func (*Image) AssignProfile ¶
AssignProfile returns a copy of the image whose embedded profile is p, without changing any pixel value. Pass nil to remove the profile.
func (*Image) ClearColor ¶
ClearColor is Pixmap.ClearColor on every frame of a copy of the image.
func (*Image) ClipPath ¶
func (m *Image) ClipPath(path Path, fn func(*Pixmap) (*Pixmap, error), opts ...DrawOption) (*Image, error)
ClipPath is Pixmap.ClipPath on every frame of a copy of the image.
func (*Image) ColorModel ¶
ColorModel implements image.Image.
func (*Image) ConvertColor ¶
func (m *Image) ConvertColor(src, dst *Profile, opts ...ColorOption) (*Image, error)
ConvertColor converts every frame from the colour space of src to that of dst and embeds dst in the result: the same arguments as Pixmap.ConvertColor. A nil src means the image's own profile (its embedded one, else the default of the colour model); a src of another colour model than a frame's is replaced by that model's default. See Pixmap.ConvertColor for what changes. NewColorTransform and ColorTransform.Convert are the same conversion with the profiles resolved once, for many images.
Example ¶
package main
import (
"fmt"
"image"
"recursiveai.org/go/oneimage"
)
func main() {
// The result embeds the destination profile.
img := oneimage.NewImage(oneimage.NewPixmap(image.Rect(0, 0, 1, 1), oneimage.RGB8))
out, err := img.AssignProfile(oneimage.DisplayP3()).ConvertColor(nil, oneimage.SRGB())
p, embedded := out.Profile()
fmt.Println(err, embedded, p.Description())
}
Output: <nil> true sRGB
func (*Image) ConvertColorContext ¶
func (m *Image) ConvertColorContext(ctx context.Context, src, dst *Profile, opts ...ColorOption) (*Image, error)
ConvertColorContext is Image.ConvertColor that stops when ctx is cancelled, between blocks of rows and between frames, returning ctx.Err().
func (*Image) ConvertPixels ¶
func (m *Image) ConvertPixels(f PixelFormat) (*Image, error)
ConvertPixels converts every frame to pixel format f (see Pixmap.Convert for the rules). The embedded profile is kept when the colour model stays the same and dropped when it changes, since it would describe other data.
func (*Image) Duration ¶
Duration returns the time one play of the animation takes: the sum of the frame delays.
func (*Image) Edit ¶
Edit returns a copy of the image in which fn has changed every frame. fn receives each frame as a Pixmap it may draw on freely; the receiver and its frames are never modified. Frames keep their delays, and the metadata is carried over. Every frame is drawn in its own pixel grid, so an animation survives the edit. The first error stops the work and is returned.
Example ¶
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func must[T any](v T, err error) T {
if err != nil {
panic(err)
}
return v
}
func main() {
img := oneimage.NewImage(oneimage.NewPixmap(image.Rect(0, 0, 2, 2), oneimage.NRGBA8))
out, err := img.Edit(func(p *oneimage.Pixmap) error {
return p.FillPath(oneimage.SolidBrush(color.NRGBA{0, 0, 255, 255}), must(oneimage.RectPath(0, 0, 1, 2)))
})
if err != nil {
panic(err)
}
_, _, _, a0 := img.At(0, 0).RGBA() // the original is untouched
r, g, b, _ := out.At(0, 0).RGBA()
fmt.Println(a0, r>>8, g>>8, b>>8)
}
Output: 0 0 0 255
func (*Image) FillColor ¶
FillColor is Pixmap.FillColor on every frame of a copy of the image.
func (*Image) FillPath ¶
FillPath is Pixmap.FillPath on every frame of a copy of the image.
func (*Image) Frame ¶
Frame returns frame i as an image of its own: one frame, the same metadata and format details. Operations on it leave m alone, so one frame of an animation can be processed and put back with Image.WithFrames. An index outside the image is an ErrOperation.
Example ¶
package main
import (
"fmt"
"image"
"time"
"recursiveai.org/go/oneimage"
)
func main() {
a := oneimage.NewPixmap(image.Rect(0, 0, 8, 8), oneimage.NRGBA8)
b := oneimage.NewPixmap(image.Rect(0, 0, 8, 8), oneimage.NRGBA8)
anim, _ := oneimage.NewAnimation(0, oneimage.Frame{Image: a, Delay: time.Second}, oneimage.Frame{Image: b, Delay: time.Second})
second, _ := anim.Frame(1)
small, _ := oneimage.Apply(second, oneimage.Resize(4, 4))
edited, _ := anim.WithFrames(anim.Frames[0], oneimage.Frame{Image: oneimage.NewPixmap(image.Rect(0, 0, 8, 8), oneimage.NRGBA8), Delay: 2 * time.Second})
fmt.Println(small.Bounds().Size(), edited.Duration())
}
Output: (4,4) 3s
func (*Image) Histogram ¶
func (m *Image) Histogram(bins int, opts ...AnalysisOption) (*Histogram, error)
Histogram counts the samples of a frame in bins equal-width bins per channel (1 to 65536); a sample v of a depth with full scale F falls in bin v·bins/(F+1) (rounded down). Colour is the straight value.
func (*Image) Profile ¶
Profile returns the profile embedded in the image (Metadata.ICC). When there is none, or its bytes are not a usable profile, it returns the default profile of the first frame's colour model and false.
func (*Image) Statistics ¶
func (m *Image) Statistics(opts ...AnalysisOption) (*Statistics, error)
Statistics computes count, minimum, maximum, mean and standard deviation of every channel of a frame (colour as the straight value). Sums are exact integers, so the result does not depend on how the work is split. A channel with no counted pixels reports zeros.
Example ¶
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func toneExampleImage() *oneimage.Image {
p := oneimage.NewPixmap(image.Rect(0, 0, 4, 4), oneimage.NRGBA8)
for y := 0; y < 4; y++ {
for x := 0; x < 4; x++ {
p.Set(x, y, color.NRGBA{R: uint8(60 * x), G: uint8(60 * y), B: 100, A: 255})
}
}
return oneimage.NewImage(p)
}
func main() {
s, _ := toneExampleImage().Statistics()
fmt.Println(s.PixelCount, s.FullScale, s.Channels[2].Mean)
}
Output: 16 255 100
func (*Image) StripMetadata ¶
StripMetadata returns a copy of img whose metadata is Metadata.Stripped. The frames are shared, not copied.
func (*Image) StrokePath ¶
StrokePath is Pixmap.StrokePath on every frame of a copy of the image.
func (*Image) WithDelays ¶
WithDelays returns a copy of m with frame i shown for delays[i]. The number of delays must equal the number of frames.
func (*Image) WithFrames ¶
WithFrames returns a copy of m with its frames replaced (loop count, metadata and details are kept), after the same checks as NewAnimation.
type Info ¶
type Info struct {
// Format is the detected format name.
Format string
// Width and Height are the canvas size.
Width, Height int
// NumFrames is the number of frames the file declares (at least 1 once
// [Identify] has normalised it).
NumFrames int
// LoopCount is the animation's play count, 0 for forever.
LoopCount int
// BitDepth is the sample depth decoding yields: 8, or 16 for 16-bit files.
BitDepth int
// HasAlpha reports whether the decoded pixels have an alpha channel.
HasAlpha bool
// HasICC, HasExif and HasXMP report which metadata blobs are present.
HasICC, HasExif, HasXMP bool
// Metadata holds the blobs themselves when the decoder's Identify read
// them; [Identify] fills the rest from the Has flags it cannot see.
Metadata Metadata
// FrameInfo lists every frame's size and delay in file order. When a
// decoder leaves it empty, [Identify] reports NumFrames frames of the canvas
// size with no delay.
FrameInfo []FrameInfo
// Details holds the format's own facts, a pointer to the format's info
// type: *[PNGInfo], *[JPEGInfo], *[GIFInfo], *[WebPInfo], *[TIFFInfo],
// *[BMPInfo] or *[ICOInfo] for the built-in formats, a type of the
// registering package for the others, nil when the format has none. Use a
// type switch or assertion; an open registry has no closed set of types.
Details any
}
Info is what Identify reports without decoding pixels.
func Identify ¶
func Identify(r io.Reader, opts ...DecodeOption) (Info, error)
Identify reports the format, size, frame count and metadata flags of the image in r without decoding pixels. Like Decode it reads the input into memory, up to Limits.MaxInputBytes.
Example ¶
package main
import (
"fmt"
"image"
"recursiveai.org/go/oneimage"
)
func main() {
data, _ := oneimage.EncodeBytes(image.NewGray(image.Rect(0, 0, 30, 20)), "png", nil)
info, err := oneimage.IdentifyBytes(data)
fmt.Println(info.Format, info.Width, info.Height, info.BitDepth, err)
}
Output: png 30 20 8 <nil>
func IdentifyBytes ¶
func IdentifyBytes(data []byte, opts ...DecodeOption) (Info, error)
IdentifyBytes is Identify for data in memory.
func IdentifyContext ¶
IdentifyContext is Identify that stops reading when ctx is cancelled.
type InfoEncoder ¶
type InfoEncoder interface {
Encoder
// EncoderInfo reports the encoder's capabilities. It must return the same
// value every time.
EncoderInfo() EncoderInfo
}
InfoEncoder is implemented by encoders that restrict their input. It is the one place a format states what it takes; new capabilities become fields of EncoderInfo rather than new interfaces.
type JPEGComponent ¶
type JPEGComponent struct {
// ID is the component identifier.
ID uint8
// H and V are the sampling factors, 1 to 4.
H, V int
}
JPEGComponent is one component of a JPEG frame.
type JPEGInfo ¶
type JPEGInfo struct {
// SOF is the frame type marker code minus 0xC0: 0 baseline, 1 extended
// sequential, 2 progressive, 9 and 10 their arithmetic-coded forms.
SOF uint8
// Precision is the bits per sample of the file: 8 or 12.
Precision int
// Progressive and Arithmetic report the coding process.
Progressive, Arithmetic bool
// Components lists the frame's components in file order.
Components []JPEGComponent
// Scans is the number of scans the file holds (read by Decode; Identify
// stops at the first one and reports 0).
Scans int
// RestartInterval is the DRI value in effect, in MCUs; 0 for none.
RestartInterval int
// JFIF is the JFIF APP0 segment, nil when absent.
JFIF *JPEGJFIF
// AdobeTransform is the transform flag of the Adobe APP14 segment (0, 1
// or 2), nil when the file has none.
AdobeTransform *uint8
// Orientation is the Exif orientation, 1 to 8; 1 when the file has none.
// Decoding never applies it; see [Orient].
Orientation int
}
JPEGInfo holds the facts a JPEG file states about itself. Decoding fills it in Image.Details and Info.Details. Colour profiles and the Adobe and JFIF markers are reported and never applied to pixels; the decoder only follows the transform flag of the Adobe marker to turn the stored components into colour.
type JPEGJFIF ¶
type JPEGJFIF struct {
// MajorVersion and MinorVersion are the JFIF version.
MajorVersion, MinorVersion uint8
// Units is 0 for an aspect ratio only, 1 for dots per inch, 2 for dots
// per centimetre.
Units uint8
// XDensity and YDensity are the pixel densities.
XDensity, YDensity uint16
}
JPEGJFIF holds the fields of the JFIF APP0 segment (JFIF 1.02).
type JPEGOptions ¶
type JPEGOptions struct {
// Quality is 1 to 100 on the libjpeg scale (the standard quantisation
// tables of T.81 Annex K scaled by 5000/q below 50 and 200-2q above);
// 0 means 75. Other values are an error.
Quality int
// Subsampling is the chroma subsampling of colour images. Gray and CMYK
// images ignore it.
Subsampling JPEGSubsampling
// Progressive writes a progressive file in ten scans (six for gray),
// using the usual spectral selection and successive approximation
// script. Progressive files always use optimised Huffman tables.
Progressive bool
// StandardTables writes the sample Huffman tables of T.81 Annex K
// instead of tables built from the image. It is ignored when Progressive
// is set, because those tables have no end-of-band codes.
StandardTables bool
// RestartInterval writes a restart marker every this many MCUs; 0 for
// none. At most 65535.
RestartInterval int
// StripMetadata leaves out the ICC profile, Exif and XMP that would
// otherwise be carried over from the image.
StripMetadata bool
}
JPEGOptions configures the JPEG encoder. The zero value gives a baseline file of quality 75, 4:2:0 subsampling and optimised Huffman tables.
type JPEGSubsampling ¶
type JPEGSubsampling uint8
JPEGSubsampling is the chroma subsampling of a JPEG encoder. The zero value is 4:2:0, which is what libjpeg-based tools choose by default.
const ( // JPEGSubsample420 halves the chroma resolution both ways (the // default). JPEGSubsample420 JPEGSubsampling = iota // JPEGSubsample422 halves it horizontally. JPEGSubsample422 // JPEGSubsample440 halves it vertically. JPEGSubsample440 // JPEGSubsample444 keeps full chroma resolution. JPEGSubsample444 )
Chroma subsampling schemes of JPEGOptions.
func (JPEGSubsampling) MarshalText ¶
func (v JPEGSubsampling) MarshalText() ([]byte, error)
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (JPEGSubsampling) String ¶
func (s JPEGSubsampling) String() string
String returns the name of the JPEGSubsampling, spelled as its text form and Parse function read it.
func (*JPEGSubsampling) UnmarshalText ¶
func (v *JPEGSubsampling) UnmarshalText(text []byte) error
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type JPEGWriter ¶
type JPEGWriter struct {
// contains filtered or unexported fields
}
JPEGWriter writes one baseline JPEG a band of rows at a time, holding about 64 rows, so an image taller than memory allows can be written as it is produced (see PNGWriter for the same idea in PNG).
Every band is coded on its own with the standard Huffman tables of T.81 Annex K (the tables cannot be built from pixels not yet seen) and joined to the next at a restart marker, so the file is an ordinary baseline JPEG with a restart interval of one band. The pixels decoded from it equal those of EncodeJPEG with StandardTables and that restart interval. Progressive output and optimised tables need the whole image and are refused.
Example ¶
JPEGWriter writes a JPEG as rows arrive, so a very tall picture never has to be in memory.
package main
import (
"bytes"
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func main() {
var out bytes.Buffer
w, _ := oneimage.NewJPEGWriter(&out, 32, 200, oneimage.RGB8, &oneimage.JPEGOptions{Quality: 90}, oneimage.Metadata{})
band := oneimage.NewPixmap(image.Rect(0, 0, 32, 50), oneimage.RGB8)
band.FillColor(color.NRGBA{R: 200, G: 100, B: 50, A: 255})
for y := 0; y < 200; y += 50 {
w.WriteRows(band)
}
fmt.Println(w.Close())
img, _ := oneimage.DecodeBytes(out.Bytes())
fmt.Println(img.Bounds().Size(), img.Format)
}
Output: <nil> (32,200) jpeg
func NewJPEGWriter ¶
func NewJPEGWriter(w io.Writer, width, height int, format PixelFormat, opts *JPEGOptions, meta Metadata) (*JPEGWriter, error)
NewJPEGWriter starts a JPEG of width x height pixels of the given pixel format. Only its colour model counts (Gray, RGB or CMYK): pixels written later are converted to 8-bit samples of that model and alpha is dropped. opts may be nil; Quality and Subsampling apply, StripMetadata leaves out meta, and Progressive, a RestartInterval or StandardTables set to false are refused. meta supplies the ICC profile and Exif (written as given, see ExifForOutput) and XMP.
func (*JPEGWriter) Close ¶
func (j *JPEGWriter) Close() error
Close writes the last band and the end-of-image marker. Fewer rows than the declared height is an error. It does not close the destination, and calling it again returns the first call's result.
func (*JPEGWriter) WriteBands ¶
WriteBands writes every band of seq with JPEGWriter.WriteRows; it does not close the writer.
type LimitError ¶
type LimitError struct {
// Format is the format being read, or empty.
Format string
// Limit names the bound, such as "pixels per frame".
Limit string
// Value is the amount asked for (0 when unknown) and Max the bound.
Value, Max int64
// Err is the underlying error, such as a limit error of a reader this
// library sits on; nil when there is none. [errors.Is] and [errors.As]
// look through it.
Err error
}
LimitError reports which limit was exceeded. It matches ErrLimit.
func (*LimitError) Error ¶
func (e *LimitError) Error() string
Error names the limit and the amount that exceeded it.
func (*LimitError) Is ¶
func (e *LimitError) Is(target error) bool
Is reports a match with ErrLimit.
func (*LimitError) Unwrap ¶
func (e *LimitError) Unwrap() error
Unwrap returns the underlying error, if any.
type Limits ¶
type Limits struct {
// MaxDimension bounds width and height. Default 65535.
MaxDimension int
// MaxPixels bounds width*height of one frame. Default 1<<28.
MaxPixels int64
// MaxTotalPixels bounds the pixels of all frames of one image. Default 1<<30.
MaxTotalPixels int64
// MaxFrames bounds the number of frames. Default 1000.
MaxFrames int
// MaxMetadataBytes bounds the decoded size of all metadata blobs (ICC,
// Exif, XMP, text) of one image. Default 16 MiB.
MaxMetadataBytes int64
// MaxExpansionRatio bounds decompressed bytes per compressed byte for
// deflate, LZW and similar. Default 1100, just above deflate's own
// maximum of about 1032.
MaxExpansionRatio float64
// MaxInputBytes bounds how much a reader is drained into memory by Decode
// and Identify. Default 1 GiB.
MaxInputBytes int64
// MaxFrameBytes bounds the memory of one decoded frame in bytes, checked by
// decoders that build a frame from a declared size (see
// [Limits.CheckFrameBytes]). Frames are held in memory in full, so the
// pixel limit alone would let a 2^28-pixel RGBA frame take a gigabyte.
// Default 512 MiB.
MaxFrameBytes int64
}
Limits bounds what a decoder may allocate and read. Every limit is checked against headers before memory is allocated, so a tiny hostile file cannot make a decoder reserve gigabytes. A zero field takes its default; a negative field turns that limit off (the hard caps below still apply).
The defaults are DefaultLimits; UnrestrictedLimits lifts all of them.
func DefaultLimits ¶
func DefaultLimits() Limits
DefaultLimits returns the limits applied when none are given.
func UnrestrictedLimits ¶
func UnrestrictedLimits() Limits
UnrestrictedLimits returns limits that are off, apart from the hard caps of 1<<24 pixels per side and 1<<32 pixels per frame.
func (Limits) CheckFrame ¶
CheckFrame verifies a frame size against the limits (resolved first, so unset fields mean the defaults) and returns a *LimitError when it is too large. format names the codec for the error message.
func (Limits) CheckFrameBytes ¶
CheckFrameBytes verifies that a frame of the given size at bytesPerPixel stays within MaxFrameBytes and returns a *LimitError when it does not. Decoders call it, after CheckFrame, with the pixel size of the buffer they are about to allocate.
func (Limits) CheckFrames ¶
CheckFrames verifies a list of frame sizes (as width, height pairs) against the frame-count, per-frame, per-dimension and total-pixel limits. It is the check a decoder runs on a file's declared frames before allocating anything.
func (Limits) CheckMetadata ¶
CheckMetadata verifies the metadata blobs against MaxMetadataBytes and returns a *LimitError when they are too large. Like every Check method it resolves the receiver itself, so unset fields mean the defaults. Text entries count with their keyword and text.
func (Limits) CheckMetadataBytes ¶
CheckMetadataBytes verifies a metadata size in bytes against MaxMetadataBytes.
func (Limits) CheckTotal ¶
CheckTotal verifies that frames frames of the given size stay within the frame-count and total-pixel limits.
type Matrix ¶
type Matrix [9]float64
Matrix is a 3x3 projective matrix in row-major order. It maps source coordinates to destination coordinates as column vectors, (x', y', w') = M * (x, y, 1), with the origin at the top-left corner of the top-left pixel (pixel edges, so a pixel centre is at +0.5), x to the right and y down. An affine map has w' = 1 (last row 0, 0, 1).
func MatrixFromQuads ¶
MatrixFromQuads returns the projective map taking the four points from to the four points to, in corresponding order. Both quadrilaterals must be convex and not degenerate, otherwise the error is an ErrOperation.
func MatrixFromRectangle ¶
MatrixFromRectangle returns the map taking the corners of a width x height rectangle (top-left, top-right, bottom-right, bottom-left) to corners.
func MatrixTaper ¶
func MatrixTaper(width, height float64, side TaperSide, corner TaperCorner, amount float64) (Matrix, error)
MatrixTaper returns the map that pulls the named edge of a width x height rectangle in to amount (0 < amount <= 1) of its length, keeping the opposite edge: a trapezoid. Other values are an ErrOperation.
func (Matrix) Affine ¶
Affine returns m as an affine map and true when its last row is 0, 0, 1 (within no tolerance: exactly), and false for a projective matrix.
func (Matrix) Inverse ¶
Inverse returns the inverse map, or an ErrUnsupported error for a singular matrix.
type Matrix3x2 ¶
type Matrix3x2 [6]float64
Matrix3x2 is the library's one affine map, written in the order SVG's matrix(a b c d e f) and canvas transforms use: a point (x, y) goes to
x' = x*M[0] + y*M[2] + M[4] y' = x*M[1] + y*M[3] + M[5]
Coordinates have their origin at the top-left corner, x to the right and y down, so a positive rotation turns clockwise on screen. The zero value maps every point to the origin; use IdentityMatrix for "no change".
Matrices compose with Matrix3x2.Mul: m.Mul(n) applies m first, then n. The chaining methods Matrix3x2.Rotate, Matrix3x2.Scale, Matrix3x2.Translate and Matrix3x2.Skew read the same way: the step they add happens after what m already does. Matrix3x2.Around moves the fixed point of a map. The 3x3 Matrix is only for perspective maps.
func RotationMatrix ¶
RotationMatrix turns points clockwise on screen (y down) by degrees about the origin. Use Matrix3x2.Around to turn about another point.
func SkewMatrix ¶
SkewMatrix is the shear in which x moves by tan(dxDegrees)*y and y by tan(dyDegrees)*x, about the origin.
func TranslationMatrix ¶
TranslationMatrix moves points by (dx, dy).
func (Matrix3x2) Around ¶
Around returns the map that does what m does as seen from the point (ox, oy): the point stays where m's linear part would leave it, so RotationMatrix(30).Around(cx, cy) turns about (cx, cy) and ScaleMatrix(2, 2).Around(ox, oy) leaves (ox, oy) fixed. Any translation already in m is kept.
Example ¶
Steps chain in reading order; Around moves the fixed point.
package main
import (
"fmt"
"recursiveai.org/go/oneimage"
)
func main() {
turn := oneimage.RotationMatrix(90).Around(10, 10)
fmt.Printf("%.0f\n", turn.Apply(oneimage.Vec2{X: 20, Y: 10}))
m := oneimage.IdentityMatrix.Scale(2, 2).Translate(1, 0)
fmt.Println(m.Apply(oneimage.Vec2{X: 3, Y: 4}))
}
Output: {10 20} {7 8}
func (Matrix3x2) Invert ¶
Invert returns the inverse map and false when m is singular or not finite.
func (Matrix3x2) Matrix ¶
Matrix returns m as a 3x3 projective matrix (last row 0, 0, 1), for Perspective and MatrixBuilder.
Example ¶
A Matrix3x2 converts to the 3x3 form perspective uses and back.
package main
import (
"fmt"
"recursiveai.org/go/oneimage"
)
func main() {
m := oneimage.TranslationMatrix(5, 6)
back, ok := m.Matrix().Affine()
fmt.Println(back == m, ok)
}
Output: true true
func (Matrix3x2) Skew ¶
Skew returns m followed by a shear about the origin (see SkewMatrix).
type MatrixBuilder ¶
type MatrixBuilder struct {
// contains filtered or unexported fields
}
MatrixBuilder composes a projective map from steps, as the image it is applied to is only known later: steps that default to the image centre (rotation, skew) or the whole image (a quad) resolve against its size. A step is appended (applied after the ones so far) or prepended (applied before them). The zero value is an empty builder; steps return the builder.
Example ¶
A MatrixBuilder composes steps that depend on the image size, such as a rotation about its centre.
package main
import (
"fmt"
"recursiveai.org/go/oneimage"
)
func main() {
b := (&oneimage.MatrixBuilder{}).AppendRotationDegrees(25).AppendTranslation(5, 0)
m, _ := b.Matrix(40, 30)
x, y, _ := m.Point(20, 15) // the centre only moves by the translation
fmt.Printf("%.1f %.1f\n", x, y)
}
Output: 25.0 15.0
func (*MatrixBuilder) AppendMatrix ¶
func (b *MatrixBuilder) AppendMatrix(m Matrix) *MatrixBuilder
AppendMatrix adds the map m after the existing steps.
func (*MatrixBuilder) AppendQuad ¶
func (b *MatrixBuilder) AppendQuad(corners [4]Vec2) *MatrixBuilder
AppendQuad adds the map taking the image rectangle to the four corners (top-left, top-right, bottom-right, bottom-left) after the existing steps.
func (*MatrixBuilder) AppendRotationAbout ¶
func (b *MatrixBuilder) AppendRotationAbout(degrees, cx, cy float64) *MatrixBuilder
AppendRotationAbout adds a clockwise rotation about (cx, cy).
func (*MatrixBuilder) AppendRotationDegrees ¶
func (b *MatrixBuilder) AppendRotationDegrees(degrees float64) *MatrixBuilder
AppendRotationDegrees adds a clockwise rotation about the image centre after the existing steps.
func (*MatrixBuilder) AppendScale ¶
func (b *MatrixBuilder) AppendScale(x, y float64) *MatrixBuilder
AppendScale adds a scaling about the origin after the existing steps.
func (*MatrixBuilder) AppendSkewAbout ¶
func (b *MatrixBuilder) AppendSkewAbout(x, y, ox, oy float64) *MatrixBuilder
AppendSkewAbout adds a shear about (ox, oy).
func (*MatrixBuilder) AppendSkewDegrees ¶
func (b *MatrixBuilder) AppendSkewDegrees(x, y float64) *MatrixBuilder
AppendSkewDegrees adds a shear about the image centre after the existing steps.
func (*MatrixBuilder) AppendTaper ¶
func (b *MatrixBuilder) AppendTaper(side TaperSide, corner TaperCorner, amount float64) *MatrixBuilder
AppendTaper adds a taper of the whole image after the existing steps.
func (*MatrixBuilder) AppendTranslation ¶
func (b *MatrixBuilder) AppendTranslation(x, y float64) *MatrixBuilder
AppendTranslation adds a translation after the existing steps.
func (*MatrixBuilder) Matrix ¶
func (b *MatrixBuilder) Matrix(width, height int) (Matrix, error)
Matrix resolves the steps for an image of width x height pixels.
func (*MatrixBuilder) PrependMatrix ¶
func (b *MatrixBuilder) PrependMatrix(m Matrix) *MatrixBuilder
PrependMatrix adds the map m before the existing steps.
func (*MatrixBuilder) PrependQuad ¶
func (b *MatrixBuilder) PrependQuad(corners [4]Vec2) *MatrixBuilder
PrependQuad adds the map taking the image rectangle to the four corners before the existing steps.
func (*MatrixBuilder) PrependRotationAbout ¶
func (b *MatrixBuilder) PrependRotationAbout(degrees, cx, cy float64) *MatrixBuilder
PrependRotationAbout adds a clockwise rotation about (cx, cy) before the existing steps.
func (*MatrixBuilder) PrependRotationDegrees ¶
func (b *MatrixBuilder) PrependRotationDegrees(degrees float64) *MatrixBuilder
PrependRotationDegrees adds a clockwise rotation about the image centre before the existing steps.
func (*MatrixBuilder) PrependScale ¶
func (b *MatrixBuilder) PrependScale(x, y float64) *MatrixBuilder
PrependScale adds a scaling about the origin before the existing steps.
func (*MatrixBuilder) PrependSkewAbout ¶
func (b *MatrixBuilder) PrependSkewAbout(x, y, ox, oy float64) *MatrixBuilder
PrependSkewAbout adds a shear about (ox, oy) before the existing steps.
func (*MatrixBuilder) PrependSkewDegrees ¶
func (b *MatrixBuilder) PrependSkewDegrees(x, y float64) *MatrixBuilder
PrependSkewDegrees adds a shear about the image centre before the existing steps.
func (*MatrixBuilder) PrependTaper ¶
func (b *MatrixBuilder) PrependTaper(side TaperSide, corner TaperCorner, amount float64) *MatrixBuilder
PrependTaper adds a taper of the whole image before the existing steps.
func (*MatrixBuilder) PrependTranslation ¶
func (b *MatrixBuilder) PrependTranslation(x, y float64) *MatrixBuilder
PrependTranslation adds a translation before the existing steps.
type Metadata ¶
type Metadata struct {
// ICC is the embedded ICC profile, nil when none. Decoders carry the bytes
// only; they never apply the profile to pixels.
ICC []byte
// Exif is the Exif block as a TIFF stream (starting "II" or "MM"), without
// any container prefix such as JPEG's "Exif\0\0".
Exif []byte
// XMP is the XMP packet.
XMP []byte
// IPTC is the IPTC-NAA block (the data of Photoshop image resource 0x0404
// in a JPEG's APP13 segment), nil when none. Only JPEG carries it.
IPTC []byte
// Orientation is the Exif orientation of the stored pixels, 1 to 8; 0 means
// not stated, which reads as 1. Decoders may set it (TIFF stores it as a
// tag of its own); otherwise [Decode] derives it from Exif. Applying the
// orientation to the pixels (see [Open]) resets it to 1.
Orientation int
// Text holds textual chunks (PNG tEXt, zTXt and iTXt) in file order.
Text []TextEntry
}
Metadata is what an image file carries besides pixels. Blobs are the bytes as stored, decompressed where the container compresses them, and are preserved through decode and encode.
func (Metadata) ColorProfile ¶
ColorProfile parses the embedded ICC profile. ok is false when there is none or it cannot be read.
func (Metadata) EffectiveOrientation ¶
EffectiveOrientation returns the orientation of the stored pixels, 1 to 8: the Orientation field when it is set, else the one in the Exif block, else 1.
func (Metadata) ReadExif ¶
func (m Metadata) ReadExif() (ExifFields, error)
ReadExif parses the common tags of m.Exif (see ParseExif). An image without an Exif block returns a *FormatError.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/oneimage"
)
func main() {
_, err := oneimage.Metadata{}.ReadExif()
fmt.Println(err)
}
Output: oneimage: exif: no Exif block
func (Metadata) Stripped ¶
Stripped returns the metadata without Exif, XMP, IPTC and text entries, and without the ICC profile unless keepICC is set. The orientation is kept: it describes the pixels, not a blob.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/oneimage"
)
func main() {
m := oneimage.Metadata{ICC: []byte("profile"), XMP: []byte("<x/>"), Orientation: 6}
s := m.Stripped(true)
fmt.Println(len(s.ICC), len(s.XMP), s.Orientation)
}
Output: 7 0 6
func (Metadata) TotalBytes ¶
TotalBytes is the combined size of the metadata blobs: ICC profile, Exif, XMP and IPTC. Text entries are not counted.
func (Metadata) WithICC ¶
WithICC returns the metadata with its ICC profile replaced; an empty profile removes it.
func (Metadata) WithOrientation ¶
WithOrientation returns the metadata with the orientation set. A value outside 1 to 8 is an ErrOperation. The Exif block is not edited here; encoders get it corrected from the image's size and orientation (see ExifForOutput).
type Op ¶
type Op interface {
// Name is the operation's snake_case name, such as "resize".
Name() string
// Params lists the parameters, defaults included, in a fixed order, as
// plain values: int, float64, bool, string (an enumerated value in
// lower-case kebab words), []int (a colour as r, g, b, a in 0..255) or
// []float64. Together with Name they describe the operation without Go
// types, so another implementation can rebuild it.
Params() []Param
// Apply runs the operation on every frame of img.
Apply(img *Image) (*Image, error)
}
Op is one image operation: an immutable value that carries its parameters, can name itself in language-neutral terms, and applies itself to every frame of an image.
Operations are built with constructors such as Resize, Crop or Rotate and run with Apply or Image.Apply. An Op never changes its input: it returns a new image (frames are new pixmaps, metadata is copied) or, when the parameters make it an identity (a crop of the whole image, a rotation by 360 degrees, a resize to the same size), the input itself. Every frame of an animation is processed. Ops are safe for concurrent use.
func AdaptiveThreshold ¶
AdaptiveThreshold binarises by comparing each pixel with the mean of its neighbourhood (Bradley's method): a pixel whose 8-bit luma is at or below limit (0..1) times the mean of the window around it becomes the lower colour, otherwise the upper one. The window reaches s−2 pixels before and s+1 after the pixel, inclusive, clipped at the edge, with s = max(1, width/16). WithColors sets the colours (default white above, black below). The result is RGBA.
func AddAlpha ¶
AddAlpha gives an image without alpha a constant alpha channel (0..1). An image that has alpha is returned unchanged.
func Affine ¶
Affine returns the operation that applies the affine map m (see Matrix3x2 for the convention) to the image, with the options of Rotate. With expansion on (the default) the canvas is the bounding box of the transformed image and its origin moves with it, so a pure translation shifts nothing visible. A singular matrix is an ErrUnsupported.
func ApplyColorMatrix ¶
func ApplyColorMatrix(m ColorMatrix) Op
ApplyColorMatrix multiplies straight colour and alpha by m. The result is RGB, and gains an alpha channel when the matrix changes alpha. The identity returns the image unchanged.
func ApplyMask ¶
ApplyMask multiplies the image's alpha by a mask image (its first frame) placed with its top-left corner at (x, y); alpha outside the mask becomes 0. The mask's alpha channel is used, or with WithMaskLuminance its luminance (weights 0.2125, 0.7154, 0.0721) times its alpha, in linear light when WithLinear is set (default false). The mask is first reduced to 8 bits. An image without alpha fails with ErrUnsupported.
Example ¶
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func toneExampleImage() *oneimage.Image {
p := oneimage.NewPixmap(image.Rect(0, 0, 4, 4), oneimage.NRGBA8)
for y := 0; y < 4; y++ {
for x := 0; x < 4; x++ {
p.Set(x, y, color.NRGBA{R: uint8(60 * x), G: uint8(60 * y), B: 100, A: 255})
}
}
return oneimage.NewImage(p)
}
func main() {
m := oneimage.NewPixmap(image.Rect(0, 0, 2, 4), oneimage.GrayAlpha8)
for y := 0; y < 4; y++ {
for x := 0; x < 2; x++ {
m.Set(x, y, color.NRGBA{255, 255, 255, 255})
}
}
out, _ := oneimage.Apply(toneExampleImage(), oneimage.ApplyMask(oneimage.NewImage(m), 0, 0))
fmt.Println(out.At(0, 0), out.At(3, 0))
}
Output: {0 0 100 255} {180 0 100 0}
func AutoLevel ¶
AutoLevel stretches the luminance histogram over the full range, like a global histogram equalization of the 8-bit BT.709 luma. By default (WithSyncChannels true) each pixel's colour is scaled by the gain the curve gives its luma, which keeps hue; otherwise every channel is mapped through the curve on its own. The result is RGB. Alpha is unchanged.
func AutoOrient ¶
func AutoOrient() Op
AutoOrient returns the operation that turns the image upright by the orientation its Exif block records (1 when it has none or cannot be read), then rewrites that tag to 1 in the result's Exif block, so applying it again changes nothing. Every frame is turned.
func BinaryDither ¶
BinaryDither reduces an image to two colours: lower (default black) and upper (default white, set with WithColors) chosen like DitherToPalette.
func BlackWhite ¶
func BlackWhite() Op
BlackWhite turns an image into a high-contrast black and white one with the gain min(1, max(0, 1.5·(r+g+b) − 1)) on every channel. The result is RGB with equal channels; alpha is unchanged.
func BokehBlur ¶
BokehBlur blurs with a disc-shaped aperture of the given radius (1..255 pixels), the look of an out-of-focus lens. components (1..6) is the number of kernel components of the aperture model; the disc here is evaluated directly, so it only has to lie in range. Colour is raised to gamma (above 0, up to 8) before averaging and lowered afterwards, so bright spots bloom; a gamma of 1 is a plain disc average. Alpha is blurred like colour; the default edge is EdgeClamp and the work is on stored values.
func BoxBlur ¶
BoxBlur blurs with a box of 2·radius+1 pixels along each axis, radius 1 to 4096. Space and edge options are those of GaussianBlur.
func BrightnessContrast ¶
BrightnessContrast changes brightness and contrast, each in -1..1 (0 is no change). Values outside the range fail with ErrOperation. Options: WithLinear (default false: the stored values), WithBrightnessMode (default BrightnessLinear).
Example ¶
Consecutive curve operations fuse into one table pass.
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func toneExampleImage() *oneimage.Image {
p := oneimage.NewPixmap(image.Rect(0, 0, 4, 4), oneimage.NRGBA8)
for y := 0; y < 4; y++ {
for x := 0; x < 4; x++ {
p.Set(x, y, color.NRGBA{R: uint8(60 * x), G: uint8(60 * y), B: 100, A: 255})
}
}
return oneimage.NewImage(p)
}
func main() {
out, _ := oneimage.Apply(toneExampleImage(), oneimage.BrightnessContrast(0.1, 0), oneimage.Invert())
fmt.Println(out.At(0, 0))
}
Output: {229 229 129 255}
func ChannelMixer ¶
ChannelMixer mixes the colour channels of an RGB image: matrix holds nine values (three per output channel: how much red, green and blue it takes) or twelve (a fourth per output channel, an offset). WithLinear (default false) chooses linear light. Alpha is unchanged.
func Clear ¶
Clear replaces every pixel by a colour. On an image with alpha every pixel becomes exactly that colour and alpha; on an image without alpha the colour is blended over the old pixels by its alpha, so an opaque colour replaces them. A gray image takes the colour's luma.
func ColorBlindness ¶
func ColorBlindness(mode BlindnessMode) Op
ColorBlindness simulates a colour-vision deficiency with ColorMatrixColorBlindness.
func Composite ¶
Composite draws overlay (its first frame) onto every frame of the image with its top-left corner at (x, y); parts outside the image are ignored, pixels outside the overlay are unchanged. Options: WithOpacity (default 1, a value of 0 returns the image unchanged), WithBlend (default BlendNormal), WithComposition (default CompSrcOver) and WithLinear (default false: blend the stored values; true blends in linear light). The result has the image's own format. An image without alpha accepts only the operators that keep it opaque (CompSrcOver, CompSrcAtop, CompDest, CompDestOver), others fail with ErrUnsupported; the colour blend modes need an RGB image.
Example ¶
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func toneExampleImage() *oneimage.Image {
p := oneimage.NewPixmap(image.Rect(0, 0, 4, 4), oneimage.NRGBA8)
for y := 0; y < 4; y++ {
for x := 0; x < 4; x++ {
p.Set(x, y, color.NRGBA{R: uint8(60 * x), G: uint8(60 * y), B: 100, A: 255})
}
}
return oneimage.NewImage(p)
}
func main() {
ov := oneimage.NewPixmap(image.Rect(0, 0, 2, 2), oneimage.NRGBA8)
for i := range ov.Pix8 {
ov.Pix8[i] = 255
}
out, _ := oneimage.Apply(toneExampleImage(),
oneimage.Composite(oneimage.NewImage(ov), 1, 1, oneimage.WithBlend(oneimage.BlendMultiply), oneimage.WithOpacity(0.5)))
fmt.Println(out.At(1, 1), out.At(0, 0))
}
Output: {60 60 100 255} {0 0 100 255}
func Convolve ¶
Convolve correlates the image with kernel (rows of equal odd length, an odd number of rows; the kernel is not flipped), divides by divisor (0 means the sum of the weights, or 1 when that is 0) and adds offset to each colour channel (of the premultiplied plane). Alpha is convolved too and clamped. Defaults: linear light, EdgeClamp.
func Crop ¶
Crop returns the operation that keeps the rectangle r of every frame, in pixel coordinates from the top-left corner. An empty rectangle or one not wholly inside the image is an ErrOperation; a rectangle that is the whole image is the identity. The result's bounds start at (0, 0).
func Curves ¶
Curves maps colour through a curve drawn through points (x, y in 0..1, at least two, distinct x). Below the first and above the last point the curve is flat. WithCurveInterpolation, WithChannel and WithLinear (default false) adjust it.
Example ¶
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func toneExampleImage() *oneimage.Image {
p := oneimage.NewPixmap(image.Rect(0, 0, 4, 4), oneimage.NRGBA8)
for y := 0; y < 4; y++ {
for x := 0; x < 4; x++ {
p.Set(x, y, color.NRGBA{R: uint8(60 * x), G: uint8(60 * y), B: 100, A: 255})
}
}
return oneimage.NewImage(p)
}
func main() {
out, _ := oneimage.Apply(toneExampleImage(), oneimage.Curves([]oneimage.Vec2{{X: 0, Y: 0}, {X: 1, Y: 0.5}}))
fmt.Println(out.At(1, 0))
}
Output: {30 0 50 255}
func DetectEdges ¶
func DetectEdges(detector EdgeDetector, grayscale bool, opts ...OpOption) Op
DetectEdges finds edges with the chosen detector. With grayscale true (the default of the descriptor; pass false for per-channel) the 8-bit luma is filtered and the result is a gray image without alpha; with false each colour channel is filtered and alpha is kept. Responses are clamped to 0..1, so negative Laplacian responses read black. The default edge is EdgeClamp.
Example ¶
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func toneExampleImage() *oneimage.Image {
p := oneimage.NewPixmap(image.Rect(0, 0, 4, 4), oneimage.NRGBA8)
for y := 0; y < 4; y++ {
for x := 0; x < 4; x++ {
p.Set(x, y, color.NRGBA{R: uint8(60 * x), G: uint8(60 * y), B: 100, A: 255})
}
}
return oneimage.NewImage(p)
}
func main() {
out, _ := oneimage.Apply(toneExampleImage(), oneimage.DetectEdges(oneimage.EdgeSobel, true))
fmt.Println(out.Width())
}
Output: 4
func DitherToPalette ¶
DitherToPalette maps an image to the colours of palette (1 to 65536 colours, alpha counts in the distance) and spreads the difference with d (DitherNone maps to the nearest colour). The default dither for the option-less call is DitherFloydSteinberg. Ordered dithers shift the colour channels by S·scale·((m+1)/n² − ½) before choosing, with S = min(255, ⌊255/(∛|palette| − 1)⌋) and m the n by n Bayer matrix; DitherBayer8x8 is the 8 by 8 matrix. Error diffusion takes palettes of at most 256 colours and chooses by RGB distance; its strength is fixed, and a scale of 0 turns every dither into nearest-colour mapping (WithDitherScale). The result is 8-bit RGB, or NRGBA when the image or a palette colour has alpha.
Example ¶
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func toneExampleImage() *oneimage.Image {
p := oneimage.NewPixmap(image.Rect(0, 0, 4, 4), oneimage.NRGBA8)
for y := 0; y < 4; y++ {
for x := 0; x < 4; x++ {
p.Set(x, y, color.NRGBA{R: uint8(60 * x), G: uint8(60 * y), B: 100, A: 255})
}
}
return oneimage.NewImage(p)
}
func main() {
bw := []color.Color{color.NRGBA{A: 255}, color.NRGBA{255, 255, 255, 255}}
out, _ := oneimage.Apply(toneExampleImage(), oneimage.DitherToPalette(bw, oneimage.DitherNone))
fmt.Println(out.At(3, 3))
}
Output: {255 255 255 255}
func EntropyCrop ¶
EntropyCrop returns the operation that cuts the image to the area with detail: a Sobel edge detection per channel on the 8-bit values (edges replicated), reduced to Rec. 709 luma and rounded to 8 bits; every pixel at or above threshold*255 counts as detail, and the smallest rectangle holding them is kept. An image without any detail is returned unchanged. The rectangle is found on the first frame and applied to all.
func Exposure ¶
Exposure scales colour by 2^stops, in -16..16. The default space is linear light (WithLinear changes it).
func Fill ¶
Fill composites a solid colour over the whole image with the same blend mode, operator and opacity options as Composite (the colour's alpha counts). On a gray image the colour is reduced to its luma first.
Example ¶
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func toneExampleImage() *oneimage.Image {
p := oneimage.NewPixmap(image.Rect(0, 0, 4, 4), oneimage.NRGBA8)
for y := 0; y < 4; y++ {
for x := 0; x < 4; x++ {
p.Set(x, y, color.NRGBA{R: uint8(60 * x), G: uint8(60 * y), B: 100, A: 255})
}
}
return oneimage.NewImage(p)
}
func main() {
out, _ := oneimage.Apply(toneExampleImage(), oneimage.Fill(color.NRGBA{R: 200, A: 255}, oneimage.WithOpacity(0.5)))
fmt.Println(out.At(0, 0))
}
Output: {100 0 50 255}
func Flatten ¶
Flatten composites the image over an opaque background (set with WithBackground, default black; the colour's alpha is ignored) and drops alpha. WithLinear (default false) blends in linear light. An image without alpha is returned unchanged.
func Flip ¶
Flip returns the operation that mirrors every frame left to right (FlipHorizontal) or top to bottom (FlipVertical). It moves pixels exactly.
func Gamma ¶
Gamma applies the power 1/gamma to colour, gamma in (0, 100]; values above 1 brighten. The default space is the stored values (WithLinear changes it).
Example ¶
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func toneExampleImage() *oneimage.Image {
p := oneimage.NewPixmap(image.Rect(0, 0, 4, 4), oneimage.NRGBA8)
for y := 0; y < 4; y++ {
for x := 0; x < 4; x++ {
p.Set(x, y, color.NRGBA{R: uint8(60 * x), G: uint8(60 * y), B: 100, A: 255})
}
}
return oneimage.NewImage(p)
}
func main() {
out, _ := oneimage.Apply(toneExampleImage(), oneimage.Gamma(2))
fmt.Println(out.At(2, 0))
}
Output: {175 0 160 255}
func GaussianBlur ¶
GaussianBlur blurs with a Gaussian of standard deviation sigma (pixels, 0 or more) along x and, with WithSigmaY, a different one along y; a sigma of 0 leaves its axis alone. The kernel reaches ceil(3·sigma) pixels. The default space is linear light with premultiplied alpha (WithLinear changes it); the default edge is EdgeClamp (WithEdge: clamp, mirror or constant; wrap is refused). A kernel wider than the image is folded back onto it. A blur whose tables would exceed about 64 million weights fails with ErrLimit.
Example ¶
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func toneExampleImage() *oneimage.Image {
p := oneimage.NewPixmap(image.Rect(0, 0, 4, 4), oneimage.NRGBA8)
for y := 0; y < 4; y++ {
for x := 0; x < 4; x++ {
p.Set(x, y, color.NRGBA{R: uint8(60 * x), G: uint8(60 * y), B: 100, A: 255})
}
}
return oneimage.NewImage(p)
}
func main() {
out, _ := oneimage.Apply(toneExampleImage(), oneimage.GaussianBlur(1, oneimage.WithLinear(false)))
fmt.Println(out.Width(), out.Height())
}
Output: 4 4
func GaussianSharpen ¶
GaussianSharpen sharpens with a two-pass kernel (twice the identity minus a Gaussian of standard deviation sigma, 0..42). The first pass is clamped to the valid range before the second. A sigma of 0 returns the image unchanged. The default space is the stored values and the default edge EdgeClamp.
func Glow ¶
Glow lays a soft spot of colour c over the centre of the area: strength max(0, 1 − 0.95·d/radius), radius defaulting to (and limited by) half the area's width. WithArea sets the area (default the whole image); nothing changes outside it.
func Grayscale ¶
Grayscale replaces colour by its BT.709 luma. The default space is linear light (WithLinear changes it). The result keeps the RGB model with equal channels unless WithGrayFormat asks for the gray model. A gray image is returned unchanged.
Example ¶
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func toneExampleImage() *oneimage.Image {
p := oneimage.NewPixmap(image.Rect(0, 0, 4, 4), oneimage.NRGBA8)
for y := 0; y < 4; y++ {
for x := 0; x < 4; x++ {
p.Set(x, y, color.NRGBA{R: uint8(60 * x), G: uint8(60 * y), B: 100, A: 255})
}
}
return oneimage.NewImage(p)
}
func main() {
out, _ := oneimage.Apply(toneExampleImage(), oneimage.Grayscale(oneimage.WithLinear(false), oneimage.WithGrayFormat(true)))
fmt.Println(out.ColorModel() == oneimage.NewImage(oneimage.NewPixmap(image.Rect(0, 0, 1, 1), oneimage.GrayAlpha8)).ColorModel(), out.At(0, 0))
}
Output: true {7 7 7 255}
func HistogramEqualization ¶
HistogramEqualization spreads the luminance histogram so the image uses the whole range. The luma (BT.709, rounded to the sample range) is binned into WithEqualization levels (default 256), each pixel gets the value (cdf − cdfMin)/(n − cdfMin) of its cumulative histogram scaled to full range, and the result is that value on all three colour channels (a gray image stays gray). A single occupied bin maps to 0. Alpha is unchanged.
WithEqualizeMethod selects EqualizeGlobal (default), or the adaptive methods that equalize per tile (interpolated between tiles) or per sliding window; adaptive methods take at most 4096 levels. WithClipLimit clips every bin to a limit (default 350) and spreads the excess evenly.
Example ¶
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func toneExampleImage() *oneimage.Image {
p := oneimage.NewPixmap(image.Rect(0, 0, 4, 4), oneimage.NRGBA8)
for y := 0; y < 4; y++ {
for x := 0; x < 4; x++ {
p.Set(x, y, color.NRGBA{R: uint8(60 * x), G: uint8(60 * y), B: 100, A: 255})
}
}
return oneimage.NewImage(p)
}
func main() {
out, _ := oneimage.Apply(toneExampleImage(), oneimage.HistogramEqualization(), oneimage.AutoLevel())
fmt.Println(out.Width())
}
Output: 4
func HueSaturationLightness ¶
HueSaturationLightness shifts the hue by hue degrees, scales saturation by 1+saturation and moves lightness toward white (positive) or black (negative) by the fraction lightness; saturation and lightness lie in -1..1. The maths is HSL, not a luminance-preserving matrix. WithLinear (default false) chooses linear light.
func Invert ¶
Invert replaces each colour value by its complement. Alpha is unchanged. WithLinear chooses linear light (default false).
func Kodachrome ¶
func Kodachrome() Op
Kodachrome gives the warm, high-contrast look of Kodachrome film with a colour matrix. Alpha is unchanged.
func Levels ¶
Levels maps inBlack..inWhite to outBlack..outWhite through a gamma, all in 0..1 with inBlack below inWhite and gamma above 0. WithChannel limits it to one channel of an RGB image; WithLinear chooses linear light (default false).
Example ¶
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func toneExampleImage() *oneimage.Image {
p := oneimage.NewPixmap(image.Rect(0, 0, 4, 4), oneimage.NRGBA8)
for y := 0; y < 4; y++ {
for x := 0; x < 4; x++ {
p.Set(x, y, color.NRGBA{R: uint8(60 * x), G: uint8(60 * y), B: 100, A: 255})
}
}
return oneimage.NewImage(p)
}
func main() {
out, _ := oneimage.Apply(toneExampleImage(), oneimage.Levels(0, 0.5, 1, 0, 1, oneimage.WithChannel(oneimage.ChannelRed)))
fmt.Println(out.At(3, 0))
}
Output: {255 0 100 255}
func Lomograph ¶
func Lomograph() Op
Lomograph gives the saturated, vignetted look of a toy camera: a colour matrix that lifts red and green, then a Vignette tinted (0, 10, 0).
func Median ¶
Median replaces each sample by the median of the (2·radius+1)² window around it, radius 1 to 127, on the stored (straight) values of every channel including alpha. It is exact at every depth: 8- and 16-bit samples are ranked on a sliding two-level histogram. The default edge is EdgeClamp; a constant edge counts as zeros.
Example ¶
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func toneExampleImage() *oneimage.Image {
p := oneimage.NewPixmap(image.Rect(0, 0, 4, 4), oneimage.NRGBA8)
for y := 0; y < 4; y++ {
for x := 0; x < 4; x++ {
p.Set(x, y, color.NRGBA{R: uint8(60 * x), G: uint8(60 * y), B: 100, A: 255})
}
}
return oneimage.NewImage(p)
}
func main() {
out, _ := oneimage.Apply(toneExampleImage(), oneimage.Median(1))
fmt.Println(out.At(0, 0))
}
Output: {0 0 100 255}
func OilPaint ¶
OilPaint paints with an oil brush: in the brushSize-square window around each pixel (1..255, shifted so it is centred; clamped at the edges) pixels are binned by their mean 8-bit intensity into levels bins (1..1024), and the pixel becomes the average colour of the fullest bin (the brightest of equally full bins). Alpha is unchanged.
func Opacity ¶
Opacity multiplies alpha by amount in 0..1; an image without alpha gains the channel. An amount of 1 returns the image unchanged.
func Pad ¶
Pad returns the operation that adds the given number of pixels on each side. The new area follows the edge mode (WithEdge, default EdgeConstant, which fills with WithBackground); clamp, mirror and wrap may reach further than the image is wide, repeating as needed. A negative amount is an ErrOperation; all zero is the identity.
func Perspective ¶
Perspective returns the operation that applies the projective map m, with the options of Rotate. All four corners of the image must land on the same side of the horizon (w' > 0, or all < 0, in which case the matrix is negated); otherwise, and for a singular matrix, the error is an ErrUnsupported. Pixels whose source lies behind the horizon show the background.
func PerspectiveBuilder ¶
func PerspectiveBuilder(b *MatrixBuilder, opts ...OpOption) Op
PerspectiveBuilder is Perspective with the matrix resolved from b for each image's size.
func PerspectiveCorners ¶
PerspectiveCorners is Perspective with the map taking the image's corners (top-left, top-right, bottom-right, bottom-left) to corners, which must form a convex quadrilateral (ErrOperation otherwise).
Example ¶
Perspective maps the image's corners onto a quadrilateral.
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func opExampleImage(w, h int) *oneimage.Image {
p := oneimage.NewPixmap(image.Rect(0, 0, w, h), oneimage.NRGBA8)
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
p.Set(x, y, color.NRGBA{R: uint8(x * 255 / w), G: uint8(y * 255 / h), B: 128, A: 255})
}
}
return oneimage.NewImage(p)
}
func main() {
img := opExampleImage(40, 30)
out, err := img.Apply(oneimage.PerspectiveCorners([4]oneimage.Vec2{{X: 8, Y: 2}, {X: 44, Y: 10}, {X: 38, Y: 36}, {X: 0, Y: 28}}))
if err != nil {
panic(err)
}
fmt.Println(out.Width(), out.Height())
}
Output: 44 34
func Pixelate ¶
Pixelate replaces each size-by-size block (size 1 or more) by the sample at its centre, (block start + size/2, clamped to the image), keeping the stored format. Size 1 returns the image unchanged.
Example ¶
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func toneExampleImage() *oneimage.Image {
p := oneimage.NewPixmap(image.Rect(0, 0, 4, 4), oneimage.NRGBA8)
for y := 0; y < 4; y++ {
for x := 0; x < 4; x++ {
p.Set(x, y, color.NRGBA{R: uint8(60 * x), G: uint8(60 * y), B: 100, A: 255})
}
}
return oneimage.NewImage(p)
}
func main() {
out, _ := oneimage.Apply(toneExampleImage(), oneimage.Pixelate(2))
fmt.Println(out.At(0, 0) == out.At(1, 1))
}
Output: true
func Polaroid ¶
func Polaroid() Op
Polaroid gives the faded, warm look of an instant print: a colour matrix, a Vignette tinted (102, 34, 0) and a Glow of (255, 153, 102) at half alpha reaching a quarter of the width.
func Posterize ¶
Posterize reduces each colour channel to levels values (2..65536). WithPosterizeMode selects the levels (default PosterizeNearest) and WithLinear the space (default false).
func Quantize ¶
Quantize reduces an image to at most colors colours (2 to 256), chosen by WithQuantizer (default QuantizerWu; the web-safe and Werner quantizers use their fixed palettes whatever colors says). WithQuantizeAlpha says whether partial transparency is kept in the palette (default) or snapped to opaque or transparent. WithDither (default DitherNone) spreads the colour error. An image that already has no more distinct colours than asked for keeps its pixels. The result is 8-bit NRGBA.
Example ¶
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func toneExampleImage() *oneimage.Image {
p := oneimage.NewPixmap(image.Rect(0, 0, 4, 4), oneimage.NRGBA8)
for y := 0; y < 4; y++ {
for x := 0; x < 4; x++ {
p.Set(x, y, color.NRGBA{R: uint8(60 * x), G: uint8(60 * y), B: 100, A: 255})
}
}
return oneimage.NewImage(p)
}
func main() {
out, _ := oneimage.Apply(toneExampleImage(), oneimage.Quantize(4))
h, _ := out.Histogram(256)
fmt.Println(out.Width(), h.PixelCount)
}
Output: 4 16
func RemoveAlpha ¶
func RemoveAlpha() Op
RemoveAlpha drops the alpha channel, keeping colour as stored (it does not flatten; see Flatten). An image without alpha is returned unchanged.
func Reorient ¶
Reorient returns the operation that turns pixels stored with Exif orientation o (1 to 8, see Orient) upright. Orientation 1 is the identity; any other value than 1 to 8 is an ErrOperation. It does not read or change metadata; see AutoOrient.
func Resize ¶
Resize returns the operation that scales an image into a width-by-height box. A zero width or height is left free: the other side then sets the scale and keeps the aspect ratio; both zero (or negative) is an ErrOperation when applied.
The scaled size follows the fit (default FitContain): the limiting side lands on the box size and the other is rounded half up, at least 1. Scaling is separable, in float32 on premultiplied alpha and, unless WithLinear(false), in linear light (sRGB is assumed for untagged colour), with pixel-centre mapping and replicated edges. Reductions of 4 or more per axis first average whole blocks of floor(ratio/2) samples. Gray, RGB, CMYK and Lab images keep their pixel format (a premultiplied or half-float format is scaled through its straight or float32 twin).
Options read: WithFit, WithAnchor, WithFilter, WithUpscale, WithLinear, WithBackground (the canvas of FitPad and FitBoxPad) and WithLimits. Parameters: width, height, fit, anchor, upscale, filter, linear, background. A resize to the image's own size is the identity.
Example ¶
Resize fits an image into a box; the fit decides what happens to the aspect ratio.
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func opExampleImage(w, h int) *oneimage.Image {
p := oneimage.NewPixmap(image.Rect(0, 0, w, h), oneimage.NRGBA8)
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
p.Set(x, y, color.NRGBA{R: uint8(x * 255 / w), G: uint8(y * 255 / h), B: 128, A: 255})
}
}
return oneimage.NewImage(p)
}
func main() {
img := opExampleImage(64, 48)
for _, fit := range []oneimage.Fit{oneimage.FitContain, oneimage.FitCover, oneimage.FitStretch, oneimage.FitPad} {
out, err := img.Apply(oneimage.Resize(60, 33, oneimage.WithFit(fit)))
if err != nil {
panic(err)
}
fmt.Println(fit, out.Width(), out.Height())
}
}
Output: contain 44 33 cover 60 33 stretch 60 33 pad 60 33
func ResizeInto ¶
ResizeInto returns the operation that scales an image to width by height (a stretch) and places it with its top-left corner at (x, y) on a canvas of canvasWidth by canvasHeight filled with the background; what falls outside the canvas is cut off. Options read: WithFilter, WithLinear, WithBackground, WithLimits.
func Rotate ¶
Rotate returns the operation that turns the image clockwise by degrees. Multiples of 90 move pixels exactly and ignore every option. Other angles resample through WithFilter (default Catmull-Rom), in linear light unless WithLinear(false); by default the canvas grows to hold the whole rotated image (WithExpand(false) keeps the size and cuts the corners) and uncovered areas show the background (WithBackground, or what WithEdge says for the other edge modes). A non-finite angle is an ErrOperation.
Example ¶
Rotate turns clockwise; angles that are not a multiple of 90 resample and, by default, grow the canvas to hold the whole result.
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func opExampleImage(w, h int) *oneimage.Image {
p := oneimage.NewPixmap(image.Rect(0, 0, w, h), oneimage.NRGBA8)
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
p.Set(x, y, color.NRGBA{R: uint8(x * 255 / w), G: uint8(y * 255 / h), B: 128, A: 255})
}
}
return oneimage.NewImage(p)
}
func main() {
img := opExampleImage(40, 30)
exact, _ := img.Apply(oneimage.Rotate(270))
free, _ := img.Apply(oneimage.Rotate(15, oneimage.WithBackground(color.NRGBA{255, 255, 255, 255})))
fixed, _ := img.Apply(oneimage.Rotate(15, oneimage.WithExpand(false)))
fmt.Println(exact.Width(), exact.Height())
fmt.Println(free.Width(), free.Height())
fmt.Println(fixed.Width(), fixed.Height())
}
Output: 30 40 47 40 40 30
func Sepia ¶
Sepia gives the image a sepia tone, blended with the original by amount in 0..1 (0 returns the image unchanged).
Example ¶
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func toneExampleImage() *oneimage.Image {
p := oneimage.NewPixmap(image.Rect(0, 0, 4, 4), oneimage.NRGBA8)
for y := 0; y < 4; y++ {
for x := 0; x < 4; x++ {
p.Set(x, y, color.NRGBA{R: uint8(60 * x), G: uint8(60 * y), B: 100, A: 255})
}
}
return oneimage.NewImage(p)
}
func main() {
out, _ := oneimage.Apply(toneExampleImage(), oneimage.Sepia(1))
fmt.Println(out.At(0, 0))
}
Output: {19 17 13 255}
func Sharpen ¶
Sharpen sharpens with an unsharp mask: each colour value moves away from its Gaussian blur (standard deviation radius) by amount times the difference; differences smaller than threshold (0..1) are left alone. Alpha is unchanged and colour stays within [0, alpha]. Options as GaussianBlur (default space linear light).
func Sobel ¶
Sobel is the gray Sobel gradient magnitude of the luma: scale·√(gx²+gy²)/4, clamped to 1 (scale above 0, 1 by default in the descriptor). The result is a gray image without alpha. The default edge is EdgeClamp.
func Threshold ¶
Threshold turns colour into black and white: a pixel whose luma (BT.709) reaches level in 0..1 becomes white, others black. WithPerChannel tests each colour channel on its own instead; WithLinear (default false) compares linear-light values. Alpha is unchanged.
Example ¶
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func toneExampleImage() *oneimage.Image {
p := oneimage.NewPixmap(image.Rect(0, 0, 4, 4), oneimage.NRGBA8)
for y := 0; y < 4; y++ {
for x := 0; x < 4; x++ {
p.Set(x, y, color.NRGBA{R: uint8(60 * x), G: uint8(60 * y), B: 100, A: 255})
}
}
return oneimage.NewImage(p)
}
func main() {
out, _ := oneimage.Apply(toneExampleImage(), oneimage.Threshold(0.3))
fmt.Println(out.At(0, 0), out.At(3, 3))
}
Output: {0 0 0 255} {255 255 255 255}
func ThumbnailOp ¶
ThumbnailOp is Resize with upscaling off unless WithUpscale(true) follows: the result never exceeds the source size. It is the one rule behind Thumbnail, ThumbnailImage and Source.Thumbnail: the image is turned upright by its Exif orientation first, and the result carries the ICC profile but not the Exif, XMP, IPTC or text blocks, which can hold a location; WithKeepMetadata(true) keeps them. Its name in descriptors is "thumbnail". Options read: those of Resize and WithKeepMetadata.
Example ¶
ThumbnailOp is the one thumbnail rule inside an operation chain: upright, scaled down, Exif and XMP dropped unless WithKeepMetadata(true).
package main
import (
"fmt"
"image"
"recursiveai.org/go/oneimage"
)
func main() {
img := oneimage.NewImage(oneimage.NewPixmap(image.Rect(0, 0, 8, 8), oneimage.NRGBA8))
img.Metadata.XMP = []byte("<x:xmpmeta/>")
out, _ := oneimage.Apply(img, oneimage.ThumbnailOp(4, 4))
kept, _ := oneimage.Apply(img, oneimage.ThumbnailOp(4, 4, oneimage.WithKeepMetadata(true)))
fmt.Println(out.Width(), len(out.Metadata.XMP), len(kept.Metadata.XMP))
}
Output: 4 0 12
func Trim ¶
Trim returns the operation that cuts away the border of pixels close to the background: it keeps the smallest rectangle holding every pixel whose channel (alpha included, 8-bit scale) differs from the background by more than threshold. The background is the top-left pixel of the first frame unless WithBackground gives one. Pixels fully transparent on both sides always match. When nothing differs, the result is the 1x1 top-left pixel. A negative threshold counts as 0. All frames are cut to the rectangle found on the first.
func Vignette ¶
Vignette darkens (or tints) the edges: colour c is blended over each pixel with strength min(1, 0.9·d/|(rx, ry)|), d being the distance from the centre of the area. radiusX and radiusY default to half the area's width and height (a value of 0 means the default; negative values fail). The area is set with WithArea (default the whole image); nothing changes outside it.
Example ¶
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func toneExampleImage() *oneimage.Image {
p := oneimage.NewPixmap(image.Rect(0, 0, 4, 4), oneimage.NRGBA8)
for y := 0; y < 4; y++ {
for x := 0; x < 4; x++ {
p.Set(x, y, color.NRGBA{R: uint8(60 * x), G: uint8(60 * y), B: 100, A: 255})
}
}
return oneimage.NewImage(p)
}
func main() {
out, _ := oneimage.Apply(toneExampleImage(), oneimage.Vignette(color.NRGBA{A: 255}, 0, 0))
fmt.Println(out.At(2, 2))
}
Output: {120 120 100 255}
type OpOption ¶
type OpOption interface {
// contains filtered or unexported methods
}
OpOption adjusts an operation built by a constructor such as Resize or Rotate. An option an operation has no use for is ignored; each constructor lists the ones it reads.
func WithAnchor ¶
WithAnchor selects where the box sits when Resize or ThumbnailOp crops or pads (default AnchorCenter).
func WithArea ¶
WithArea limits Vignette and Glow to a rectangle (default the whole image). The effect centres on the rectangle and is zero outside it.
func WithBackground ¶
WithBackground sets the colour of areas the result has no source for (canvas padding, the corners of a rotated image). Read by Resize, ThumbnailOp, ResizeInto, Rotate, Affine, Perspective, Pad, Trim and Flatten. The default is transparent black. An image without an alpha channel keeps only the colour. color.NRGBA values are used exactly; other colours are converted.
func WithBlend ¶
WithBlend selects the blend mode of Composite and Fill (default BlendNormal).
func WithBrightnessMode ¶
func WithBrightnessMode(m BrightnessMode) OpOption
WithBrightnessMode selects the formula of BrightnessContrast (default BrightnessLinear).
func WithChannel ¶
WithChannel selects the colour channel of Levels and Curves (default ChannelAll).
func WithClipLimit ¶
WithClipLimit turns on histogram clipping for HistogramEqualization at limit counts per bin (default 350 when clipping is on without a limit). The excess is spread evenly over all bins.
func WithColors ¶
WithColors sets the colours AdaptiveThreshold and BinaryDither give to pixels above (upper, default white) and at or below (lower, default black) their threshold. A nil colour keeps the default.
func WithComposition ¶
func WithComposition(a AlphaComposition) OpOption
WithComposition selects the Porter–Duff operator of Composite and Fill (default CompSrcOver).
func WithCurveInterpolation ¶
func WithCurveInterpolation(i CurveInterpolation) OpOption
WithCurveInterpolation selects how Curves joins its points (default CurveMonotone).
func WithDither ¶
WithDither selects the dither of Quantize (default DitherNone). It is read only by Quantize and ignored by every other op: DitherToPalette and BinaryDither take their dither as an argument, and GIF encoding takes it from GIFOptions.Dither.
func WithDitherScale ¶
WithDitherScale scales the strength of the dither of Quantize, DitherToPalette and BinaryDither (default 1): ordered dithers scale their threshold amplitude, error diffusion the diffused error. At 0 every dither is a plain nearest-colour mapping.
func WithEdge ¶
WithEdge selects what samples outside the source see (default EdgeConstant; EdgeClamp for filters). Read by Rotate, Affine, Perspective, Pad, BoxBlur, Convolve, GaussianBlur, GaussianSharpen, Sharpen, BokehBlur, DetectEdges and Sobel.
func WithEqualization ¶
WithEqualization sets the options of HistogramEqualization: the number of luminance levels (default 256) and the number of tiles per side for the adaptive-tile method (default 8).
func WithEqualizeMethod ¶
func WithEqualizeMethod(m EqualizeMethod) OpOption
WithEqualizeMethod selects the algorithm of HistogramEqualization (default EqualizeGlobal).
func WithExpand ¶
WithExpand chooses whether Rotate, Affine or Perspective grows the canvas to hold the whole transformed image (the default) or keeps the source size.
func WithFilter ¶
WithFilter selects the resampling kernel (default FilterAuto). Read by Resize, ThumbnailOp, ResizeInto, Rotate, Affine and Perspective.
func WithFit ¶
WithFit selects how Resize fits the box (default FitContain); ThumbnailOp reads it too.
func WithGrayFormat ¶
WithGrayFormat makes Grayscale return a gray-model image instead of an RGB image holding equal channels (default false).
func WithKeepMetadata ¶
WithKeepMetadata makes ThumbnailOp (and so Thumbnail, ThumbnailImage and Source.Thumbnail) keep the Exif, XMP, IPTC and text blobs it drops by default (they can carry location and other private data). The ICC profile is always kept, and the Exif block is corrected for the new size and orientation when the image is saved.
func WithLinear ¶
WithLinear chooses the space an operation works in: true converts sRGB-encoded colour to linear light and back, false works on the stored values. Alpha is always premultiplied for the maths. The default differs by operation and is stated on each one. Read by Resize, ThumbnailOp, ResizeInto, Rotate, Affine, Perspective, BoxBlur, Convolve, GaussianBlur, GaussianSharpen, Sharpen, Composite, Fill, ChannelMixer, Flatten, Grayscale, HueSaturationLightness, Threshold, BrightnessContrast, Curves, Exposure, Gamma, Invert, Levels and Posterize; for the tone operations "linear" means the sRGB curve.
func WithMaskLuminance ¶
WithMaskLuminance makes ApplyMask read the mask's luminance (weighted by its alpha) instead of its alpha channel.
func WithOpacity ¶
WithOpacity scales the source alpha of Composite and Fill (default 1).
func WithPerChannel ¶
WithPerChannel makes Threshold compare each colour channel on its own instead of the luma (default false; ignored for gray images).
func WithPosterizeMode ¶
func WithPosterizeMode(m PosterizeMode) OpOption
WithPosterizeMode selects the levels of Posterize (default PosterizeNearest).
func WithQuantizeAlpha ¶
func WithQuantizeAlpha(a QuantizeAlpha) OpOption
WithQuantizeAlpha selects how Quantize treats alpha (default QuantizeAlphaFull).
func WithQuantizer ¶
WithQuantizer selects the palette method of Quantize (default QuantizerWu).
func WithSigmaY ¶
WithSigmaY gives GaussianBlur a different sigma along y; the default is the x sigma. A sigma of 0 leaves that axis unblurred.
func WithSyncChannels ¶
WithSyncChannels chooses whether AutoLevel scales the three colour channels by one common gain (true, the default, which keeps hue) or maps each channel through the luminance curve.
func WithUpscale ¶
WithUpscale turns enlarging on or off for Resize and ThumbnailOp (default on for Resize; thumbnails turn it off). With it off, a fit that would enlarge keeps the image size.
type PNGColor ¶
type PNGColor uint8
PNGColor selects how the encoder chooses the PNG colour type.
const ( // PNGColorAuto writes truecolour or gray as supplied, except that an 8-bit // RGB or NRGBA image of at most 256 distinct colours becomes a palette // image. The pixels read back are identical either way. PNGColorAuto PNGColor = iota // PNGColorTruecolor never writes a palette: the colour type follows the // pixel format (gray, gray+alpha, RGB or NRGBA). PNGColorTruecolor // PNGColorIndexed always writes a palette. An image of more than // MaxColors colours is reduced with a median-cut quantizer (16-bit samples // are first rounded to 8 bits); fewer colours are kept exactly. PNGColorIndexed )
func (PNGColor) MarshalText ¶
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (*PNGColor) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type PNGFilter ¶
type PNGFilter uint8
PNGFilter selects the scanline filter.
const ( // PNGFilterAdaptive picks, per scanline, the filter with the smallest sum // of absolute values (the heuristic PNG 3rd ed. section 12.8 suggests). // Palette and sub-byte images use no filter. PNGFilterAdaptive PNGFilter = iota // PNGFilterNone, PNGFilterSub, PNGFilterUp, PNGFilterAverage and // PNGFilterPaeth use that filter type on every scanline. PNGFilterNone // PNGFilterSub predicts each byte from the one to its left. PNGFilterSub // PNGFilterUp predicts each byte from the one above. PNGFilterUp // PNGFilterAverage predicts from the mean of the left and upper bytes. PNGFilterAverage // PNGFilterPaeth predicts with the Paeth predictor (PNG section 9.4). PNGFilterPaeth )
func (PNGFilter) MarshalText ¶
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (*PNGFilter) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type PNGInfo ¶
type PNGInfo struct {
// ColorType and BitDepth are the IHDR values: colour type 0 (gray), 2
// (truecolour), 3 (palette), 4 (gray with alpha) or 6 (truecolour with
// alpha), and the bits per sample (1, 2, 4, 8 or 16).
ColorType, BitDepth uint8
// Interlaced reports Adam7 interlacing.
Interlaced bool
// Animated reports that an acTL chunk is present (APNG).
Animated bool
// Gamma is the gAMA value in units of 1/100000, nil when absent.
Gamma *uint32
// Chromaticities holds the eight cHRM values (white point x, y, red x, y,
// green x, y, blue x, y, each in units of 1/100000), nil when absent.
Chromaticities *[8]uint32
// SRGBIntent is the sRGB rendering intent (0 to 3), nil when absent.
SRGBIntent *uint8
// CICP holds the cICP code points (colour primaries, transfer function,
// matrix coefficients, full-range flag), nil when absent.
CICP *[4]uint8
}
PNGInfo holds the facts a PNG file states about itself. Decoding fills it in Image.Details and Info.Details; the colour chunks are reported as stored and are never applied to pixels (the specification leaves colour management to the application). When an *Image carrying a *PNGInfo is encoded as PNG, the colour chunks that are set are written again.
type PNGOptions ¶
type PNGOptions struct {
// Color chooses the colour type; the default is PNGColorAuto.
Color PNGColor
// Compression is the deflate level: PNGNoCompression (stored), 0 for the
// default (6), or 1 to 9. Other values are an error.
Compression int
// Filter is the scanline filter; the default is PNGFilterAdaptive.
Filter PNGFilter
// MaxColors bounds the palette for PNGColorIndexed, 2 to 256; 0 means 256.
MaxColors int
// StripMetadata leaves out the ICC profile, Exif, XMP, text chunks and
// colour chunks that would otherwise be carried over from the image.
StripMetadata bool
}
PNGOptions configures the PNG encoder. The zero value is the default.
type PNGWriter ¶
type PNGWriter struct {
// contains filtered or unexported fields
}
PNGWriter writes one PNG image a band of rows at a time, holding only the row being compressed, so an image taller than memory allows can be written as it is produced (for example from Source.Bands through a per-band operation).
It writes a still, non-interlaced image in the pixel format given to NewPNGWriter: gray or RGB, 8 or 16 bits, with or without straight alpha. Palette output and the choice of the smallest colour type need every pixel first, so PNGColorIndexed is refused and PNGColorAuto means truecolor (the colour type the format names). Apart from that the bytes are those EncodePNG writes with PNGColorTruecolor for the same pixels and options.
func NewPNGWriter ¶
func NewPNGWriter(w io.Writer, width, height int, format PixelFormat, opts *PNGOptions, meta Metadata) (*PNGWriter, error)
NewPNGWriter starts a PNG of width x height pixels in the given pixel format and writes everything that precedes the pixel data. opts may be nil. meta supplies the ICC profile, Exif, XMP and text entries (unless opts.StripMetadata); it is written as given, so pass a block corrected with ExifForOutput when the size or orientation changed.
Example ¶
The streaming writers share one shape: WriteBands leaves the file open and Close finishes it, as often as it is called.
package main
import (
"bytes"
"fmt"
"image"
"recursiveai.org/go/oneimage"
)
func main() {
var buf bytes.Buffer
w, _ := oneimage.NewPNGWriter(&buf, 4, 4, oneimage.NRGBA8, nil, oneimage.Metadata{})
band := oneimage.NewPixmap(image.Rect(0, 0, 4, 4), oneimage.NRGBA8)
_ = w.WriteBands(func(yield func(*oneimage.Pixmap, error) bool) { yield(band, nil) })
fmt.Println(w.Close(), w.Close())
img, err := oneimage.DecodeBytes(buf.Bytes())
fmt.Println(err, img.Width())
}
Output: <nil> <nil> <nil> 4
func (*PNGWriter) Close ¶
Close finishes the image. Fewer rows than the declared height is an error and leaves the output unfinished. It does not close the destination, and calling it again returns the first call's result.
func (*PNGWriter) WriteBands ¶
WriteBands writes every band of seq with PNGWriter.WriteRows; it does not close the writer, so `w.WriteBands(src.Bands(0, image.Rectangle{}, 0))` followed by PNGWriter.Close copies a frame. It stops at the first error, which is returned (a band error from the sequence included).
type Param ¶
type Param struct {
// Name is the parameter's language-neutral name, such as "sigma".
Name string
// Value is its value: a bool, int, float64, string or a slice of int or
// float64.
Value any
}
Param is one named parameter of an Op.
type Path ¶
type Path struct {
// contains filtered or unexported fields
}
Path is a list of figures made of straight lines and Bézier curves, in pixel coordinates (x to the right, y down). A Path is immutable: every method returns a new one. The zero Path is empty. Arcs (SVG elliptical arcs included) are stored as cubics of at most 90 degrees.
Build paths with PathBuilder, the shape functions (RectPath, EllipsePath, ...) and ParsePath.
func CirclePath ¶
CirclePath is the circle with centre (cx, cy) and radius r.
func CombinePaths ¶
CombinePaths concatenates the figures of the paths.
func EllipsePath ¶
EllipsePath is the ellipse with centre (cx, cy) and radii rx and ry, from the right-most point clockwise on screen.
func ParsePath ¶
ParsePath reads SVG path data (SVG 1.1 section 8: M L H V C S Q T A Z in both cases). Parsing is strict: the data must start with a move, and the first malformed command fails the whole parse with a FormatError (SVG's "render up to the error" is not done). Data is bounded to 64 MiB and 2^25 commands. Empty data is an empty path.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/oneimage"
)
func must[T any](v T, err error) T {
if err != nil {
panic(err)
}
return v
}
func main() {
p := must(oneimage.ParsePath("M10 10 H30 V20 Z"))
b, _ := p.Bounds()
fmt.Println(p.SVG())
fmt.Println(b.Width(), b.Height(), p.FigureCount())
_, err := oneimage.ParsePath("L1 1") // data must start with a move
fmt.Println(err != nil)
}
Output: M 10 10 L 30 10 L 30 20 Z 20 10 1 true
func PolygonPath ¶
PolygonPath joins the points with straight segments and closes the figure. Fewer than two points give an empty path.
func PolylinePath ¶
PolylinePath joins the points with straight segments and leaves the figure open. Fewer than two points give an empty path.
func RectPath ¶
RectPath is the rectangle with corner (x, y) and size w by h, clockwise on screen from the top-left corner. A negative size is normalised.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/oneimage"
)
func must[T any](v T, err error) T {
if err != nil {
panic(err)
}
return v
}
func main() {
r := must(oneimage.RectPath(2, 3, 10, 4))
c := must(oneimage.CirclePath(0, 0, 5))
rb, _ := r.Bounds()
cb, _ := c.Bounds()
fmt.Println(rb.Min, rb.Max)
fmt.Printf("%.2f %.2f\n", cb.Min.X, cb.Max.Y)
}
Output: {2 3} {12 7} -5.00 5.00
func RegularPolygonPath ¶
RegularPolygonPath has sides vertices on a circle of radius r around (cx, cy). The first vertex is straight up, turned clockwise by rotationDegrees; the vertices run clockwise on screen. Fewer than three sides are refused.
func RoundedRectPath ¶
RoundedRectPath is a rectangle whose corners are quarter circles of radius r, limited to half the shorter side.
func StarPath ¶
func StarPath(cx, cy float64, prongs int, innerRadius, outerRadius, rotationDegrees float64) (Path, error)
StarPath has prongs tips on the outer radius with inner vertices between them; the first tip is straight up, turned clockwise by rotationDegrees. Fewer than two prongs are refused.
func UnionAll ¶
func UnionAll(paths []Path, opts ...PathOption) (Path, error)
UnionAll merges any number of paths in one pass, each read under the rule of WithRule. Each path is resolved on its own first, so a path wound the other way, or with holes, does not cancel its neighbours.
func (Path) Boolean ¶
Boolean combines the regions the two paths enclose, each read under its own rule (WithRule for p, WithClipRule for other), so self-intersecting paths, shapes with holes and paths that overlap themselves work as they do when filled.
The result is a path of straight-edged closed polygons: curves are flattened first (see WithTolerance). Outer contours and holes run in opposite directions, nothing overlaps and no two edges cross, so the result fills the same under either rule. Collinear vertices are removed, edges two shapes share on opposite sides vanish, and shapes that only touch at a point stay separate. An empty region gives an empty path.
The work is exact: every coordinate is rounded to a grid of 1/256 pixel, intersection points are rounded to it too, and every decision is made in integer arithmetic, so collinear and coincident edges, shared vertices and slivers need no tolerances. Coordinates beyond +-33,554,432, more than 2^22 flattened segments or an arrangement of more than 2^23 pieces fail with a LimitError.
func (Path) Bounds ¶
func (p Path) Bounds() (PathBounds, bool)
Bounds returns the tight bounding box of the path, curve extrema included, and false for an empty path.
func (Path) CurrentPoint ¶
CurrentPoint returns the end of the last segment (the start of the last figure when it is closed) and false for an empty path.
func (Path) FigureCount ¶
FigureCount returns the number of figures that hold at least one segment.
func (Path) Flatten ¶
Flatten turns curves into straight segments that stay within tolerance pixels of the true curve; the tolerance must be positive (DefaultFlatnessTolerance is the usual one). A result over MaxFlattenedPoints points fails with a LimitError.
func (Path) Intersect ¶
func (p Path) Intersect(other Path, opts ...PathOption) (Path, error)
Intersect is Boolean with BoolIntersection.
func (Path) Length ¶
Length returns the length of the path flattened to tolerance (in pixels, positive), closing segments included.
func (Path) Offset ¶
func (p Path) Offset(distance float64, join StrokeJoin, opts ...PathOption) (Path, error)
Offset grows (distance above 0) or shrinks (below 0) the region p encloses under WithRule: the region united with, or minus, the band of points within |distance| of its boundary. The band is the boundary stroked with the join (and, for JoinMiter, the limit of WithMiterLimit), so corners of the result follow the join where the boundary turns away from the offset and stay sharp elsewhere. Shrinking removes parts thinner than twice the distance. The result is a path of non-overlapping polygons as for Path.Boolean; a distance of 0 resolves the path.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/oneimage"
)
func must[T any](v T, err error) T {
if err != nil {
panic(err)
}
return v
}
func main() {
sq := must(oneimage.RectPath(0, 0, 20, 20))
in := must(sq.Offset(-2, oneimage.JoinMiter))
b, _ := in.Bounds()
fmt.Println(b.Min, b.Max)
}
Output: {2 2} {18 18}
func (Path) Outline ¶
Outline returns the stroke of path as a path: closed contours that, filled non-zero, cover exactly the stroke (one contour per open figure or dash, two per closed figure). Curves are flattened to tolerance first (positive); round joins and caps are exact cubic arcs. A width of 0 gives an empty path. Contours may overlap where parts of the stroke do; use Path.Resolve for non-overlapping polygons.
func (Path) Resolve ¶
func (p Path) Resolve(rule FillRule, opts ...PathOption) (Path, error)
Resolve rewrites the region p encloses under rule as non-overlapping polygons (the result of Path.Boolean with an empty second path).
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/oneimage"
)
func must[T any](v T, err error) T {
if err != nil {
panic(err)
}
return v
}
func main() {
var b oneimage.PathBuilder
b.MoveTo(0, 0).LineTo(40, 0).LineTo(40, 40).LineTo(0, 40).Close()
b.MoveTo(10, 10).LineTo(30, 10).LineTo(30, 30).LineTo(10, 30).Close()
both := must(b.Path())
ring := must(both.Resolve(oneimage.FillEvenOdd))
fmt.Println(ring.FigureCount()) // outer boundary and the hole
}
Output: 2
func (Path) Reverse ¶
Reverse returns the path with every figure traversed backwards: the same shape with the opposite winding.
func (Path) SVG ¶
SVG writes the path as SVG path data (M, L, Q, C and Z only: arcs are stored as cubics).
func (Path) Subtract ¶
func (p Path) Subtract(other Path, opts ...PathOption) (Path, error)
Subtract is Boolean with BoolDifference: p minus other.
func (Path) Transform ¶
Transform returns the path with every point mapped by m. A map that leaves the finite range makes drawing the path fail.
func (Path) Union ¶
func (p Path) Union(other Path, opts ...PathOption) (Path, error)
Union is Boolean with BoolUnion.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/oneimage"
)
func must[T any](v T, err error) T {
if err != nil {
panic(err)
}
return v
}
func main() {
a := must(oneimage.RectPath(0, 0, 20, 20))
b := must(oneimage.RectPath(10, 10, 20, 20))
u := must(a.Union(b))
x := must(a.Xor(b))
ub, _ := u.Bounds()
fmt.Println(ub.Min, ub.Max, u.FigureCount(), x.FigureCount())
}
Output: {0 0} {30 30} 1 2
type PathBounds ¶
type PathBounds struct {
// Min is the corner with the smallest coordinates.
Min Vec2
// Max is the corner with the largest coordinates.
Max Vec2
}
PathBounds is an axis-aligned box.
type PathBuilder ¶
type PathBuilder struct {
// contains filtered or unexported fields
}
PathBuilder assembles a Path. The zero value is ready to use. Errors (NaN or infinite coordinates, too many commands) are remembered and reported by Path.
A segment added when no figure is open starts a new figure at the current point, which after Close is the start of the figure just closed. A MoveTo that is followed by another MoveTo (or by nothing) leaves no trace.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/oneimage"
)
func must[T any](v T, err error) T {
if err != nil {
panic(err)
}
return v
}
func main() {
var b oneimage.PathBuilder
b.MoveTo(0, 0).LineTo(10, 0).QuadTo(15, 5, 10, 10).Close()
p := must(b.Path())
fmt.Println(p.SVG())
}
Output: M 0 0 L 10 0 Q 15 5 10 10 Z
func (*PathBuilder) AddPath ¶
func (b *PathBuilder) AddPath(p Path) *PathBuilder
AddPath appends every figure of p.
func (*PathBuilder) ArcTo ¶
func (b *PathBuilder) ArcTo(rx, ry, rotationDegrees float64, large, sweep bool, x, y float64) *PathBuilder
ArcTo adds an SVG elliptical arc (SVG 1.1 appendix F.6) to (x, y): radii rx and ry, an x-axis rotation in degrees, and the large-arc and sweep flags. Radii too small to reach are scaled up; a zero radius gives a straight line; an arc that ends where it starts adds nothing.
func (*PathBuilder) Close ¶
func (b *PathBuilder) Close() *PathBuilder
Close closes the open figure with a straight segment to its start.
func (*PathBuilder) CubicTo ¶
func (b *PathBuilder) CubicTo(c1x, c1y, c2x, c2y, x, y float64) *PathBuilder
CubicTo adds a cubic Bézier with control points (c1x, c1y) and (c2x, c2y) ending at (x, y).
func (*PathBuilder) CurrentPoint ¶
func (b *PathBuilder) CurrentPoint() Vec2
CurrentPoint returns where the next segment would start.
func (*PathBuilder) LineTo ¶
func (b *PathBuilder) LineTo(x, y float64) *PathBuilder
LineTo adds a straight segment to (x, y).
func (*PathBuilder) MoveTo ¶
func (b *PathBuilder) MoveTo(x, y float64) *PathBuilder
MoveTo starts a new figure at (x, y).
func (*PathBuilder) Path ¶
func (b *PathBuilder) Path() (Path, error)
Path returns the path built so far, or the first error.
func (*PathBuilder) QuadTo ¶
func (b *PathBuilder) QuadTo(cx, cy, x, y float64) *PathBuilder
QuadTo adds a quadratic Bézier with control point (cx, cy) ending at (x, y).
func (*PathBuilder) Reset ¶
func (b *PathBuilder) Reset() *PathBuilder
Reset discards the figures built so far (not a remembered error).
type PathOption ¶
type PathOption func(*pathOpts)
PathOption adjusts a path operation.
func WithClipRule ¶
func WithClipRule(r FillRule) PathOption
WithClipRule sets the fill rule that reads the second path of a boolean operation (default FillNonZero).
func WithMiterLimit ¶
func WithMiterLimit(l float64) PathOption
WithMiterLimit sets the miter limit of Path.Offset (default 4; at least 1).
func WithRule ¶
func WithRule(r FillRule) PathOption
WithRule sets the fill rule that reads the subject path (default FillNonZero). For UnionAll, Path.Resolve and Path.Offset it reads every path.
func WithTolerance ¶
func WithTolerance(t float64) PathOption
WithTolerance sets the flattening tolerance in pixels used to turn curves into segments first (default DefaultFlatnessTolerance); it must be positive.
type Pen ¶
type Pen struct {
// contains filtered or unexported fields
}
Pen describes how to stroke a path: a brush, a width, and the shape of corners, ends and dashes. A Pen is a value; the With methods return a changed copy. The zero Pen has no brush and draws nothing; build one with NewPen, SolidPen or a preset.
Defaults: width 1, miter joins with a limit of 4, butt caps, no dashes. The stroke is centred on the path, half the width each side, and always filled with the non-zero rule, so a translucent pen is even where it crosses itself. A stroke given a transform is scaled by it, width included.
func DashDotDotPen ¶
DashDotDotPen has the pattern 3 on, 1 off, 1 on, 1 off, 1 on, 1 off, in widths.
func DashDotPen ¶
DashDotPen has the pattern 3 on, 1 off, 1 on, 1 off, in widths.
func (Pen) WithDash ¶
WithDash returns the pen with a dash pattern of alternating on and off lengths in path units, starting with on; an odd-length pattern is repeated once (SVG). The offset moves the start into the pattern and may be negative. Every figure restarts the pattern at its start. A nil or empty pattern means a solid line.
func (Pen) WithJoin ¶
func (p Pen) WithJoin(j StrokeJoin) Pen
WithJoin returns the pen with the given corner shape.
func (Pen) WithMiterLimit ¶
WithMiterLimit returns the pen with the given miter limit (at least 1).
type PixelFormat ¶
type PixelFormat struct {
// Model is the colour model: gray, RGB, CMYK or Lab.
Model ColorModel
// Sample is the type of one sample: 8 or 16-bit integer, half or single
// float.
Sample SampleType
// Alpha says whether there is an alpha channel and whether the colour
// channels are premultiplied by it.
Alpha AlphaMode
}
PixelFormat describes how a Pixmap stores a pixel: colour model, sample type and alpha mode. Channels are interleaved: colour channels first, then alpha.
func BestFormat ¶
func BestFormat(src PixelFormat, supported []PixelFormat) (PixelFormat, bool)
BestFormat picks, from the formats an encoder takes, the one that keeps the most of a frame stored in src: the same sample type or the next wider one rather than a narrower one, the same colour model (gray widens to RGB only when gray is not offered), alpha kept when the source has it. It returns false when supported is empty. Among equals the earlier entry wins.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/oneimage"
)
func main() {
// An encoder that takes gray, RGB and RGBA is given a gray frame as gray.
f, _ := oneimage.BestFormat(oneimage.Gray8, []oneimage.PixelFormat{oneimage.RGB8, oneimage.Gray8, oneimage.NRGBA8})
fmt.Println(f == oneimage.Gray8)
}
Output: true
func (PixelFormat) BitDepth ¶
func (f PixelFormat) BitDepth() int
BitDepth returns the bits of one sample.
func (PixelFormat) BytesPerPixel ¶
func (f PixelFormat) BytesPerPixel() int
BytesPerPixel returns the storage size of one pixel, alpha included.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/oneimage"
)
func main() {
fmt.Println(oneimage.CMYK16.BytesPerPixel(), oneimage.NRGBAF16.ColorChannels(), oneimage.LabF32.Channels())
}
Output: 8 3 3
func (PixelFormat) BytesPerSample ¶
func (f PixelFormat) BytesPerSample() int
BytesPerSample returns the storage size of one sample: 1, 2 or 4.
func (PixelFormat) Channels ¶
func (f PixelFormat) Channels() int
Channels returns the number of interleaved channels, alpha included.
func (PixelFormat) ColorChannels ¶
func (f PixelFormat) ColorChannels() int
ColorChannels returns the number of colour channels, alpha excluded.
func (PixelFormat) HasAlpha ¶
func (f PixelFormat) HasAlpha() bool
HasAlpha reports whether the format has an alpha channel.
func (PixelFormat) String ¶
func (f PixelFormat) String() string
String returns the format as "model/sample" with the alpha mode, such as "rgb/uint8".
func (PixelFormat) Valid ¶
func (f PixelFormat) Valid() bool
Valid reports whether the format is one a Pixmap can hold.
type Pixmap ¶
type Pixmap struct {
// Rect is the pixmap's bounds in pixels; Min need not be (0, 0).
Rect image.Rectangle
// Format is the sample type, colour model and alpha mode of the pixels.
Format PixelFormat
// Stride is the distance between vertically adjacent pixels in samples of
// the pixel slice in use, not in bytes: a row has Format.Channels() times
// Rect.Dx() samples, so Stride is at least that. See [Pixmap.StrideBytes].
Stride int
// Pix8 holds 8-bit samples (Format.Sample is Uint8); otherwise nil.
Pix8 []uint8
// Pix16 holds 16-bit samples, or half-float bits (Format.Sample is Uint16
// or Float16); otherwise nil.
Pix16 []uint16
// PixF holds float32 samples (Format.Sample is Float32); otherwise nil.
PixF []float32
}
Pixmap is oneimage's concrete raster: a rectangle of interleaved samples in one PixelFormat. It implements image.Image and [draw.Image] and is what decoders return for non-indexed images.
Exactly one of Pix8, Pix16 and PixF is non-nil, chosen by Format.Sample: Pix8 for Uint8, Pix16 for Uint16 and Float16 (half-precision bits), PixF for Float32. Stride is in samples, not bytes (image.RGBA.Stride is in bytes; Pixmap.StrideBytes gives the byte figure), and a row y starts at (y-Rect.Min.Y)*Stride.
The zero Pixmap is an empty image: reading it is safe and gives nothing.
Reading a pixel through At returns a standard colour value: straight-alpha formats give color.NRGBA/NRGBA64 (gray without alpha gives color.Gray and Gray16), premultiplied ones give color.RGBA/RGBA64, 8-bit CMYK gives color.CMYK. Float32 pixels are clamped to 16 bits.
func FromImage ¶
FromImage returns img as a Pixmap. The common standard-library types are recognised without going through At: image.Gray, image.NRGBA, image.RGBA and image.CMYK share their samples with the result (so writing to the result writes to img), image.Gray16, image.NRGBA64, image.RGBA64, image.YCbCr and image.Paletted are converted in one pass. Any other image is read through At into 16-bit NRGBA. A *Pixmap is returned as is, and a *Image gives its first frame.
A nil image returns nil.
func NewPixmap ¶
func NewPixmap(r image.Rectangle, f PixelFormat) *Pixmap
NewPixmap allocates a zeroed Pixmap. It panics when the format is invalid or the rectangle is so large its size overflows int; decoders check the sizes against Limits first.
func NewPixmapFromBytes ¶
NewPixmapFromBytes builds a pixmap of the given size and format from packed samples, the inverse of Pixmap.CopyRegion: rows start stride bytes apart (stride 0 means tightly packed), samples are interleaved, 16-bit and float samples are big-endian. The data is copied. A zero or oversized size, an invalid format, a stride shorter than a row or data shorter than the last row is an ErrOperation. Width and height are checked against DefaultLimits before anything is allocated.
Example ¶
NewPixmapFromBytes turns packed samples, such as a frame buffer, into a Pixmap; CopyRegion goes the other way.
package main
import (
"fmt"
"recursiveai.org/go/oneimage"
)
func main() {
raw := []byte{255, 0, 0, 255, 0, 255, 0, 255} // two RGBA pixels
pm, _ := oneimage.NewPixmapFromBytes(2, 1, oneimage.NRGBA8, raw, 0)
fmt.Println(pm.At(0, 0), pm.At(1, 0))
}
Output: {255 0 0 255} {0 255 0 255}
func Orient ¶
Orient returns p permuted so that it is upright, given the Exif orientation o of the stored pixels (Exif 2.32 table 6): 2 mirrors left to right, 3 rotates by 180 degrees, 4 mirrors top to bottom, 5 transposes, 6 rotates 90 degrees clockwise, 7 transverses and 8 rotates 90 degrees counter-clockwise. Orientation 1 returns p itself; the others return a new Pixmap with bounds starting at the origin (swapped width and height for 5 to 8). Any other value is an ErrOperation.
Example ¶
package main
import (
"fmt"
"image"
"recursiveai.org/go/oneimage"
)
func main() {
p := oneimage.NewPixmap(image.Rect(0, 0, 3, 2), oneimage.Gray8)
copy(p.Pix8, []uint8{0, 1, 2, 3, 4, 5})
q, _ := oneimage.Orient(p, 6) // rotate 90 degrees clockwise
fmt.Println(q.Rect.Dx(), q.Rect.Dy(), q.Pix8)
}
Output: 2 3 [3 0 4 1 5 2]
func (*Pixmap) ClearColor ¶
ClearColor replaces every pixel with c (converted to the pixmap's format; an alpha-less pixmap is mixed with its content by c's alpha).
func (*Pixmap) ClipPath ¶
ClipPath runs fn on a copy of the pixmap and keeps its result only inside path: pixels outside are left as they are, pixels inside become the copy's result, and pixels along the edge mix the two by the path's coverage (exact area, or the pixel-centre test with WithoutAntialiasing) on premultiplied values of the stored encoding. fn sees the whole pixmap, so a blur at the edge draws on pixels outside the path; it must return a pixmap of the same size, which is converted back to the pixmap's format if it differs. Options are WithFillRule, WithoutAntialiasing, WithTransform and WithFlatness.
Example ¶
package main
import (
"fmt"
"image"
"recursiveai.org/go/oneimage"
)
func must[T any](v T, err error) T {
if err != nil {
panic(err)
}
return v
}
func main() {
pm := oneimage.NewPixmap(image.Rect(0, 0, 4, 1), oneimage.Gray8)
region := must(oneimage.RectPath(0.5, 0, 2, 1))
// Whatever the function does to its copy shows only inside the region.
err := pm.ClipPath(region, func(c *oneimage.Pixmap) (*oneimage.Pixmap, error) {
for i := range c.Pix8 {
c.Pix8[i] = 200
}
return c, nil
})
if err != nil {
panic(err)
}
fmt.Println(pm.Pix8)
}
Output: [100 200 100 0]
func (*Pixmap) CloneRegion ¶
CloneRegion returns a copy of the pixels in r (relative to the pixmap's bounds). A rectangle that is empty or reaches outside the pixmap is an error.
func (*Pixmap) ColorModel ¶
ColorModel implements image.Image. It is the model of the colour At returns.
func (*Pixmap) Convert ¶
func (p *Pixmap) Convert(f PixelFormat) (*Pixmap, error)
Convert returns p in format f. The result is a new Pixmap, or p itself when the format already matches. Rules:
- Sample types convert by scaling: 8 to 16 bits is v*257, 16 to 8 bits rounds to nearest, floats are clamped to 0..1 for integer targets.
- Gray to RGB repeats the value; RGB to gray uses BT.709 luma of the encoded values (no colour management).
- A missing alpha channel is filled opaque; dropping alpha discards it, un-premultiplying first so the colour kept is the straight colour.
- Straight to premultiplied multiplies colour by alpha with rounding; premultiplied to straight divides, with transparent pixels becoming (0, 0, 0, 0).
CMYK and Lab sources and targets convert through the default profiles (DefaultProfile) with relative colorimetric intent and black point compensation; within CMYK or within Lab only the sample type and alpha mode change. Lab samples other than Float32 hold L/100 and (a+128)/255.
func (*Pixmap) ConvertColor ¶
func (p *Pixmap) ConvertColor(src, dst *Profile, opts ...ColorOption) (*Pixmap, error)
ConvertColor converts p from the colour space of src to that of dst. A nil src means the default profile of p's colour model (DefaultProfile). The result has dst's colour model (gray, RGB, CMYK or Lab), p's sample type (Lab always Float32) and p's alpha mode; the alpha channel is carried through untouched and premultiplied colour is unpremultiplied around the conversion. p's colour model must match src's. Image.ConvertColor takes the same arguments for every frame of an image, and NewColorTransform resolves the profiles once for many pixmaps.
Example ¶
package main
import (
"fmt"
"image"
"recursiveai.org/go/oneimage"
)
func main() {
// Convert sRGB pixels to Display P3: the same colours, new numbers.
p := oneimage.NewPixmap(image.Rect(0, 0, 2, 1), oneimage.RGB8)
copy(p.Pix8, []uint8{255, 0, 0, 128, 128, 128})
q, err := p.ConvertColor(oneimage.SRGB(), oneimage.DisplayP3())
fmt.Println(err, q.Format, q.Pix8)
}
Output: <nil> rgb/uint8 [234 51 35 128 128 128]
func (*Pixmap) CopyFromImage ¶
CopyFromImage replaces the pixels at (x, y) (relative to the pixmap's bounds) with those of src, converted to the pixmap's format. A source that reaches outside the pixmap is an error and nothing changes.
func (*Pixmap) CopyRegion ¶
CopyRegion writes the pixels of the rectangle r (in the coordinates of p.Rect) into dst, row after row, each row starting stride bytes after the previous one. Samples are packed as PackedRowBytes says, with 16-bit and float samples big-endian (the order PNG stores them in). Bytes of dst between the end of a row and the start of the next are not touched.
A rectangle that is empty or not inside the pixmap, a stride shorter than a row, or a dst too small for the last row is an ErrOperation; nothing is written then.
func (*Pixmap) DrawBeziers ¶
func (p *Pixmap) DrawBeziers(pen Pen, points []Vec2, opts ...DrawOption) error
DrawBeziers strokes a chain of cubic Béziers: the first point, then three points (two controls and an end) for every curve; points left over are ignored.
func (*Pixmap) DrawEllipse ¶
func (p *Pixmap) DrawEllipse(pen Pen, cx, cy, rx, ry float64, opts ...DrawOption) error
DrawEllipse strokes the outline of an ellipse.
func (*Pixmap) DrawLine ¶
func (p *Pixmap) DrawLine(pen Pen, from, to Vec2, opts ...DrawOption) error
DrawLine strokes the straight line from one point to another.
func (*Pixmap) DrawPolygon ¶
func (p *Pixmap) DrawPolygon(pen Pen, points []Vec2, opts ...DrawOption) error
DrawPolygon strokes the closed figure through the points.
func (*Pixmap) DrawPolyline ¶
func (p *Pixmap) DrawPolyline(pen Pen, points []Vec2, opts ...DrawOption) error
DrawPolyline strokes the open figure through the points.
Example ¶
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func main() {
pm := oneimage.NewPixmap(image.Rect(0, 0, 12, 12), oneimage.Gray8)
pen := oneimage.DashPen(color.NRGBA{255, 255, 255, 255}, 2) // dashes 6 long, gaps 2
if err := pm.DrawPolyline(pen, []oneimage.Vec2{{0, 6}, {12, 6}}); err != nil {
panic(err)
}
fmt.Println(pm.Pix8[5*12 : 6*12])
}
Output: [255 255 255 255 255 255 0 0 255 255 255 255]
func (*Pixmap) DrawRect ¶
func (p *Pixmap) DrawRect(pen Pen, x, y, w, h float64, opts ...DrawOption) error
DrawRect strokes the outline of a rectangle.
func (*Pixmap) FillColor ¶
func (p *Pixmap) FillColor(c color.NRGBA, opts ...DrawOption) error
FillColor paints one colour over the whole pixmap with the options' blend mode, composition, opacity and linear-light setting; there is no shape, so transform, clip and rule options are ignored.
func (*Pixmap) FillPath ¶
func (p *Pixmap) FillPath(brush Brush, path Path, opts ...DrawOption) error
FillPath paints brush where path covers the pixmap. Coordinates are in pixels from the top-left of the pixmap's bounds; pixel (i, j) covers [i, i+1) x [j, j+1) and its centre is (i+0.5, j+0.5).
Coverage is the exact area of the shape inside each pixel (the signed-area method) under the fill rule, or the pixel-centre test with WithoutAntialiasing. The brush's colour is combined with the pixels under it by the blend mode and composition at full strength, then mixed back by the coverage on premultiplied values. Colours are those of the pixmap's own values; nothing is converted unless WithLinearLight is given. Gray pixmaps take the Rec. 709 luma of the result. CMYK and Lab pixmaps are not supported.
A path that flattens to more than MaxFlattenedPoints points, or a transform that leaves the finite range, fails; the pixmap is unchanged in that case unless the failure comes after painting began (it cannot).
Example ¶
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func must[T any](v T, err error) T {
if err != nil {
panic(err)
}
return v
}
func main() {
pm := oneimage.NewPixmap(image.Rect(0, 0, 4, 4), oneimage.NRGBA8)
// pixel (0,0) is a quarter covered, the interior is fully covered
p := must(oneimage.PolygonPath([]oneimage.Vec2{{0.5, 0.5}, {3.5, 0.5}, {3.5, 3.5}, {0.5, 3.5}}))
if err := pm.FillPath(oneimage.SolidBrush(color.NRGBA{255, 0, 0, 255}), p); err != nil {
panic(err)
}
fmt.Println(pm.Pix8[0:4], pm.Pix8[20:24])
}
Output: [255 0 0 64] [255 0 0 255]
func (*Pixmap) Opaque ¶
Opaque reports whether every pixel is fully opaque. Formats without alpha are always opaque.
func (*Pixmap) PackedRowBytes ¶
PackedRowBytes returns the bytes one row of width pixels takes in the packed form Pixmap.CopyRegion writes: interleaved samples, one byte each for 8-bit formats, two for 16-bit and half floats, four for float32.
func (*Pixmap) Row8 ¶
Row8 returns the samples of row y (y in Rect coordinates) of a Uint8 pixmap, or nil when the format or row does not fit. The slice aliases the pixmap.
func (*Pixmap) Set ¶
Set implements draw.Image. The colour is converted to the pixmap's format (to gray by BT.709 luma where the format has no colour). Pixels outside the bounds are ignored. CMYK and Lab pixmaps ignore Set.
func (*Pixmap) SetRegion ¶
SetRegion overwrites the rectangle r (in the coordinates of p.Rect) with packed samples, the inverse of Pixmap.CopyRegion: rows start stride bytes apart in src (stride 0 means tightly packed). A rectangle that is empty or not inside the pixmap, a stride shorter than a row or a src too short for the last row is an ErrOperation; nothing changes then.
func (*Pixmap) StdImage ¶
StdImage returns p as the closest standard-library image type. 8-bit Gray, NRGBA and premultiplied RGBA share their samples with p (image.Gray, image.NRGBA, image.RGBA), as does 8-bit CMYK (image.CMYK); RGB8 is widened to image.NRGBA; 16-bit formats are copied into image.Gray16, image.NRGBA64 or image.RGBA64; every other format goes through image.NRGBA64.
func (*Pixmap) StrideBytes ¶
StrideBytes is the distance between vertically adjacent pixels in bytes, the figure image.RGBA.Stride and the other standard types call Stride: the sample stride times the size of one sample (1, 2 or 4 bytes).
func (*Pixmap) StrokePath ¶
func (p *Pixmap) StrokePath(pen Pen, path Path, opts ...DrawOption) error
StrokePath paints the stroke of path with the pen's brush. The stroke is the outline of Path.Outline filled non-zero, transformed by WithTransform (which scales the width too, as in SVG) and positioned as SVG positions strokes: centred on the path. Curves are flattened to a tolerance of 0.1 pixel after the transform. A pen of width 0 draws nothing; a pen without a brush is an error. Other options are as for Pixmap.FillPath (the fill rule is ignored).
Example ¶
package main
import (
"fmt"
"image"
"image/color"
"recursiveai.org/go/oneimage"
)
func must[T any](v T, err error) T {
if err != nil {
panic(err)
}
return v
}
func main() {
pm := oneimage.NewPixmap(image.Rect(0, 0, 8, 8), oneimage.Gray8)
line := must(oneimage.ParsePath("M0 4 L8 4"))
pen := oneimage.SolidPen(color.NRGBA{255, 255, 255, 255}, 2)
if err := pm.StrokePath(pen, line); err != nil {
panic(err)
}
fmt.Println(pm.Pix8[2*8], pm.Pix8[3*8], pm.Pix8[4*8], pm.Pix8[5*8])
}
Output: 0 255 255 0
type Polyline ¶
type Polyline struct {
// Points are the vertices in order.
Points []Vec2
// Closed says the last vertex joins back to the first.
Closed bool
}
Polyline is one flattened figure.
type PosterizeMode ¶
type PosterizeMode uint8
PosterizeMode selects how Posterize picks its levels.
const ( PosterizeNearest PosterizeMode = iota PosterizeBuckets )
The modes. PosterizeNearest rounds to the nearest of n evenly spaced levels. PosterizeBuckets splits the range into n equal buckets and gives each the level at its position, so the top bucket reaches full scale.
func ParsePosterizeMode ¶
func ParsePosterizeMode(s string) (PosterizeMode, error)
ParsePosterizeMode reads "nearest" or "buckets".
func (PosterizeMode) MarshalText ¶
func (v PosterizeMode) MarshalText() ([]byte, error)
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (PosterizeMode) String ¶
func (m PosterizeMode) String() string
String returns the name of the PosterizeMode, spelled as its text form and Parse function read it.
func (*PosterizeMode) UnmarshalText ¶
func (v *PosterizeMode) UnmarshalText(text []byte) error
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type Profile ¶
type Profile struct {
// contains filtered or unexported fields
}
Profile is a parsed ICC profile (version 2 or 4): RGB and gray matrix/TRC profiles and profiles built on lut8, lut16, lutAToB and lutBToA tables for gray, RGB, CMYK and Lab colour spaces. A Profile is immutable and safe for concurrent use. Obtain one from ParseProfile, from the built-in constructors (SRGB, DisplayP3, GenericCMYK, ...) or from an image's embedded profile with Image.Profile.
func BuiltinProfile ¶
BuiltinProfile returns a built-in profile by its kebab-case name: "srgb", "srgb-compact", "display-p3", "wide-gamut-rgb", "prophoto", "rec2020", the "linear-" variants of those (and "linear-gray"), "gray", "lab-d50" and "generic-cmyk". The default profile of a colour model is available through DefaultProfile. This is the lookup by name, for configuration and command lines; SRGB, DisplayP3 and the other named constructors return the same profiles for code that knows what it wants.
func DefaultProfile ¶
func DefaultProfile(m ColorModel) *Profile
DefaultProfile returns the profile assumed for untagged data of a colour model: sRGB for RGB, the gray profile with the sRGB curve for gray, the generic CMYK profile and CIE Lab D50.
func DisplayP3 ¶
func DisplayP3() *Profile
DisplayP3 returns the Display P3 profile (P3 primaries, D65, sRGB curve).
func GenericCMYK ¶
func GenericCMYK() *Profile
GenericCMYK returns the library's generic CMYK profile, the default for untagged CMYK data. It was generated from the FOGRA39 characterization data (ISO 12647-2 coated paper) published by Fogra; the profile is the library's own and implies no certification or endorsement by Fogra.
func GrayProfile ¶
func GrayProfile() *Profile
GrayProfile returns the gray profile with the sRGB transfer curve, the default for gray data.
func LabD50 ¶
func LabD50() *Profile
LabD50 returns the CIE Lab (D50) space, the default for Lab data.
func ParseProfile ¶
ParseProfile reads an ICC profile. The profile's bytes are kept exactly, so Profile.Bytes returns what was read. Device-link, abstract and named-colour profiles, ICC.2 (iccMAX) profiles, unknown colour spaces, truncated data, tag tables that run past the data and profiles missing the tags their colour model needs are refused with an error matching ErrFormat; a well-formed profile using tables this library cannot evaluate (more than four channels) matches ErrUnsupported. Profiles larger than DefaultLimits' MaxMetadataBytes are refused with ErrLimit.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/oneimage"
)
func main() {
p, err := oneimage.ParseProfile(oneimage.DisplayP3().Bytes())
fmt.Println(err, p.Model(), p.Description(), p.MajorVersion(), p.IsLinear())
_, err = oneimage.ParseProfile([]byte("not a profile"))
fmt.Println(err != nil)
}
Output: <nil> rgb Display P3 4 false true
func ParseProfileLimits ¶
ParseProfileLimits is ParseProfile with explicit limits (only MaxMetadataBytes applies).
func ProPhoto ¶
func ProPhoto() *Profile
ProPhoto returns the ProPhoto RGB profile (D50, gamma 1.8).
func SRGB ¶
func SRGB() *Profile
SRGB returns the sRGB profile (ICC v4, parametric transfer curve), the same profile as BuiltinProfile("srgb"). It is the default for RGB data.
func SRGBCompact ¶
func SRGBCompact() *Profile
SRGBCompact returns a minimal sRGB profile (description, white point, colorants and one shared curve) for embedding in small outputs.
func WideGamutRGB ¶
func WideGamutRGB() *Profile
WideGamutRGB returns the Adobe RGB (1998)-compatible profile: its primaries, D65 white and a 563/256 power curve.
func (*Profile) Bytes ¶
Bytes returns the profile as ICC data. The slice is shared: do not modify it.
func (*Profile) Description ¶
Description returns the profile's description text ("" when it has none).
func (*Profile) IsLinear ¶
IsLinear reports whether the profile is a matrix or gray profile whose transfer curves are all the identity (linear light).
func (*Profile) LinearVariant ¶
LinearVariant returns the same colour space with linear transfer curves, or nil when the profile has none (look-up table, CMYK and Lab profiles). A linear profile is its own variant.
func (*Profile) MajorVersion ¶
MajorVersion returns the ICC major version, 2 or 4.
func (*Profile) Model ¶
func (p *Profile) Model() ColorModel
Model returns the colour model of the profile's device space.
type QuantizeAlpha ¶
type QuantizeAlpha uint8
QuantizeAlpha says what Quantize does with partial transparency.
const ( QuantizeAlphaFull QuantizeAlpha = iota QuantizeAlphaBinary )
QuantizeAlphaFull keeps alpha as part of the colour (the default). QuantizeAlphaBinary makes every pixel fully opaque or fully transparent first (alpha of 128 and above is opaque).
func ParseQuantizeAlpha ¶
func ParseQuantizeAlpha(s string) (QuantizeAlpha, error)
ParseQuantizeAlpha reads "full" or "binary".
func (QuantizeAlpha) MarshalText ¶
func (v QuantizeAlpha) MarshalText() ([]byte, error)
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (QuantizeAlpha) String ¶
func (m QuantizeAlpha) String() string
String returns the name of the QuantizeAlpha, spelled as its text form and Parse function read it.
func (*QuantizeAlpha) UnmarshalText ¶
func (v *QuantizeAlpha) UnmarshalText(text []byte) error
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type Quantizer ¶
type Quantizer uint8
Quantizer selects how an encoder chooses a palette for an image that has more colours than fit.
const ( // QuantizerWu minimises variance over a colour histogram (Xiaolin Wu's // method). It is the default. QuantizerWu Quantizer = iota // QuantizerOctree merges the least-used leaves of a colour tree. QuantizerOctree // QuantizerWebSafe uses the 139 distinct CSS Color 4 named colours, // whatever the image holds. QuantizerWebSafe // QuantizerWerner uses a fixed palette of 110 colours in the manner of // Werner's Nomenclature of Colours. QuantizerWerner )
Quantizers.
func ParseQuantizer ¶
ParseQuantizer reads a quantizer name as Quantizer.String writes it.
func (Quantizer) MarshalText ¶
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (*Quantizer) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type ReaderAtDecoder ¶
type ReaderAtDecoder interface {
Decoder
// IdentifyReaderAt is [Decoder.Identify] over a file of size bytes.
IdentifyReaderAt(r io.ReaderAt, size int64, lim Limits) (Info, error)
// DecodeReaderAt is [Decoder.Decode] over a file of size bytes.
DecodeReaderAt(r io.ReaderAt, size int64, req *DecodeRequest) (*Image, error)
}
ReaderAtDecoder is implemented by decoders that can read a file lazily from an io.ReaderAt instead of holding all of it in memory: a tiled format fetching only the tiles a region needs, for example. OpenReaderAt uses it when the format's decoder has it and keeps no copy of the file; for every other decoder the core reads the whole input into memory first. The contract of Decoder applies: hostile input, no panic, every allocation within the limits.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry is a set of formats and default limits: a configuration limited to the formats a caller chose. The process-wide registry that RegisterFormat fills serves the package-level functions; a Registry serves any call given WithRegistry (or WithEncodeRegistry). It is safe for concurrent use.
Formats are tried in the order they were added, and the first whose signature matches wins, so a catch-all format added last only sees what the earlier ones refused.
Example ¶
package main
import (
"fmt"
"image"
"recursiveai.org/go/oneimage"
)
func main() {
png, _ := oneimage.LookupFormat("png")
all := oneimage.Format{Name: "any", Sniff: func([]byte) bool { return true }}
// The first format whose signature matches wins.
reg, err := oneimage.NewRegistry(png, all)
if err != nil {
fmt.Println(err)
return
}
data, _ := oneimage.EncodeBytes(oneimage.NewPixmap(image.Rect(0, 0, 1, 1), oneimage.NRGBA8), "png", nil)
f, _ := reg.Detect(data)
g, _ := reg.Detect([]byte("something else"))
fmt.Println(f.Name, g.Name)
}
Output: png any
func DefaultRegistry ¶
func DefaultRegistry() *Registry
DefaultRegistry returns a registry holding a copy of the process-wide formats at this moment, in registration order. Formats registered later are not added to it.
func NewRegistry ¶
NewRegistry returns a registry holding the given formats, in order. A format without a name or signature test, or with a name already present, makes it fail: the error joins every such failure (see errors.Join), each an ErrOperation, and the registry is nil.
Example (Error) ¶
The registry reports every format it refuses.
package main
import (
"fmt"
"recursiveai.org/go/oneimage"
)
func main() {
_, err := oneimage.NewRegistry(oneimage.Format{Name: "nosniff"})
fmt.Println(err != nil)
}
Output: true
func (*Registry) Add ¶
Add appends a format. An empty name, a missing Sniff or a name that is already present (ignoring ASCII case) is an ErrOperation.
func (*Registry) Detect ¶
Detect returns the first format whose signature test accepts head (the first SniffLength bytes of the data).
func (*Registry) ForExtension ¶
ForExtension finds a format by file extension or path, as FormatForExtension does.
func (*Registry) Limits ¶
Limits returns the limits of the registry, resolved: DefaultLimits filled in for fields never set.
func (*Registry) Lookup ¶
Lookup finds a format by name, ignoring ASCII case, or else by extension, as LookupFormat does.
type RenderingIntent ¶
type RenderingIntent uint8
RenderingIntent is an ICC rendering intent: how colours outside the destination's gamut and the white and black points are treated when converting between profiles.
const ( // RelativeColorimetric maps the source white to the destination white and // clips out-of-gamut colours. It is the default. RelativeColorimetric RenderingIntent = iota // Perceptual uses the profiles' perceptual tables where they have them. Perceptual // Saturation uses the saturation tables where they exist. Saturation // AbsoluteColorimetric keeps colours as measured, scaling by the media // white points (a paper white is not mapped to white). Black point // compensation does not apply. AbsoluteColorimetric )
The four intents of ICC.1 clause 6.3.4.
func (RenderingIntent) MarshalText ¶
func (v RenderingIntent) MarshalText() ([]byte, error)
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (RenderingIntent) String ¶
func (i RenderingIntent) String() string
String returns the name of the RenderingIntent, spelled as its text form and Parse function read it.
func (*RenderingIntent) UnmarshalText ¶
func (v *RenderingIntent) UnmarshalText(text []byte) error
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type Repetition ¶
type Repetition uint8
Repetition says what a gradient does for positions outside 0..1.
const ( // GradientClamp extends the first and last colours. GradientClamp Repetition = iota // GradientRepeat starts over every unit, negative positions too. GradientRepeat // GradientReflect runs back and forth. GradientReflect // GradientDontFill leaves positions outside 0..1 transparent (both ends // inclusive). GradientDontFill )
Gradient repetitions.
func (Repetition) MarshalText ¶
func (v Repetition) MarshalText() ([]byte, error)
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (Repetition) String ¶
func (v Repetition) String() string
String returns the lower-case name, or Repetition(n) for an unknown value.
func (*Repetition) UnmarshalText ¶
func (v *Repetition) UnmarshalText(text []byte) error
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type RowDecoder ¶
type RowDecoder interface {
// DecodeRows decodes frame number frame (0-based), or the rectangle
// req.Region of it when that is not empty, and calls yield with
// consecutive bands of at most rows rows, top to bottom. A band's bounds
// start at x = 0 and at y = the band's first row counted from the top of
// the region. The band is only valid until yield returns: the decoder may
// reuse its memory for the next one. An error from yield stops the decode
// and is returned unchanged.
//
// The core checks what it is given: a band that does not start at the
// next row, is not as wide as the region, is empty, or reaches past the
// region's last row makes yield return an error matching [ErrOperation];
// the decoder should return it.
//
// handled == false, with a nil error and before any yield, means this
// file cannot be streamed (interlaced PNG, animation frames that depend
// on earlier ones) and the caller should decode it another way.
DecodeRows(data []byte, req *DecodeRequest, frame, rows int, yield func(band *Pixmap) error) (handled bool, err error)
}
RowDecoder is implemented by decoders that can deliver a frame's rows in order while holding only a few of them, so a very large image can be processed in bands with memory that does not depend on its height. PNG (non-interlaced) and TIFF implement it; other decoders are reached through Source.Bands by decoding the frame and cutting it into bands.
type SampleType ¶
type SampleType uint8
SampleType is how one channel value is stored.
const ( Uint8 SampleType = iota + 1 Uint16 Float16 Float32 )
Sample types. Uint8 and Uint16 span 0..max of their size; Float16 holds IEEE 754 half-precision bits in a uint16; Float32 is nominally 0..1 but may leave that range for wide-gamut or HDR data.
func (SampleType) Bits ¶
func (s SampleType) Bits() int
Bits returns the size of one sample in bits.
func (SampleType) MarshalText ¶
func (v SampleType) MarshalText() ([]byte, error)
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (SampleType) String ¶
func (s SampleType) String() string
String returns the name of the SampleType, spelled as its text form and Parse function read it.
func (*SampleType) UnmarshalText ¶
func (v *SampleType) UnmarshalText(text []byte) error
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type Sampling ¶
type Sampling uint8
Sampling is how an image brush reads its source.
const ( // SampleNearest takes the source pixel under the centre of each pixel. SampleNearest Sampling = iota // SampleBilinear blends the four source pixels around the centre, on // premultiplied colour; tiles wrap without a seam, and an untiled // source fades over half a source pixel at its edge. SampleBilinear )
Samplings.
func (Sampling) MarshalText ¶
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (*Sampling) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type SolidColorBrush ¶
type SolidColorBrush interface {
Brush
// SolidColor returns the colour (NRGBA, 0..1) and true.
SolidColor() ([4]float32, bool)
}
SolidColorBrush is implemented by one-colour brushes; the engine then skips the per-row call.
type Source ¶
type Source struct {
// contains filtered or unexported fields
}
Source is an image file opened for reading: its facts are known at once and its pixels are decoded when first asked for, frame by frame, and kept until Source.Release. Region reads decode only the needed part when the format's decoder can.
Opening reads the header facts only (see Identify); damaged pixel data shows at the first read unless WithValidate asked for a full decode up front. The compressed bytes are held in memory. A Source is safe for concurrent use.
func Open ¶
func Open(data []byte, opts ...DecodeOption) (*Source, error)
Open opens an image held in memory. The data is used without copying and must not change while the Source is in use. Options: WithLimits, WithValidate, WithAutoOrient, WithFormat, WithRegistry, WithSourceCheck.
Example ¶
package main
import (
"fmt"
"image"
"recursiveai.org/go/oneimage"
)
func main() {
img := oneimage.NewPixmap(image.Rect(0, 0, 40, 30), oneimage.NRGBA8)
data, _ := oneimage.EncodeBytes(img, "png", nil)
// Open reads the header only; pixels are decoded when first asked for.
src, err := oneimage.Open(data)
if err != nil {
fmt.Println(err)
return
}
info := src.Info()
fmt.Println(info.Format, info.Width, info.Height, src.NumFrames())
// A region is the same rectangle of the whole frame.
part, _ := src.Region(0, image.Rect(10, 5, 14, 8))
fmt.Println(part.Bounds())
}
Output: png 40 30 1 (0,0)-(4,3)
func OpenContext ¶
OpenContext is Open with a context: opening, and every later read of the returned Source (Source.Frame, Source.Region, Source.Bands, ...), stops with ctx.Err() once ctx is cancelled. The Source keeps ctx for its whole life, so give it one that outlives the reads you want to make.
func OpenReader ¶
func OpenReader(r io.Reader, opts ...DecodeOption) (*Source, error)
OpenReader is Open for a reader, which is read to its end first (up to Limits.MaxInputBytes).
func OpenReaderAt ¶
OpenReaderAt is Open for a random-access source of the given size, such as a file the caller opened. The compressed bytes are read once to open the Source; Source.Release then drops them too, together with the decoded pixels, and the next read fetches them from r again (so r must stay open while the Source is used; pair it with WithSourceCheck to notice a file that changed).
func OpenReaderAtContext ¶
func OpenReaderAtContext(ctx context.Context, r io.ReaderAt, size int64, opts ...DecodeOption) (*Source, error)
OpenReaderAtContext is OpenReaderAt with the context of OpenContext.
func OpenReaderContext ¶
OpenReaderContext is OpenReader with the context of OpenContext.
func (*Source) Bands ¶
Bands calls for frame i of the file, or for the rectangle r of it (an empty r means the whole frame), the bands of at most rows rows, top to bottom, as Pixmaps whose bounds start at x = 0 and at y = the band's first row counted from the top of r. rows <= 0 picks about one mebibyte per band.
Memory depends on the format. For PNG (not interlaced, not animated) and TIFF only the band is held, whatever the image's height; this is how an image taller than Limits.MaxFrameBytes allows can be read, filtered and written out (see PNGWriter). For every other format, and when the file's orientation has to be applied, the frame is decoded whole (subject to the limits) and cut into bands, which saves nothing but gives one interface.
A band is valid only until the next iteration: copy it to keep it. The compressed file stays in memory, as everywhere in Source. The iterator yields the first error, if any, and then stops; breaking out of the loop stops the decode.
Example ¶
Bands reads a picture a few rows at a time. For a PNG, a TIFF or a baseline JPEG only the band is in memory, however tall the image is; here the bands are inverted and written straight to a new PNG with a PNGWriter.
package main
import (
"bytes"
"fmt"
"image"
"recursiveai.org/go/oneimage"
)
func gradientPNG(w, h int) []byte {
pm := oneimage.NewPixmap(image.Rect(0, 0, w, h), oneimage.RGB8)
for y := 0; y < h; y++ {
row := pm.Row8(y)
for x := 0; x < w; x++ {
row[3*x], row[3*x+1], row[3*x+2] = byte(x), byte(y), 128
}
}
data, _ := oneimage.EncodeBytes(pm, "png", nil)
return data
}
func main() {
src, _ := oneimage.Open(gradientPNG(32, 100), oneimage.WithAutoOrient(false))
var out bytes.Buffer
w, _ := oneimage.NewPNGWriter(&out, 32, 100, oneimage.RGB8, nil, oneimage.Metadata{})
bands := 0
for band, err := range src.Bands(0, image.Rectangle{}, 32) {
if err != nil {
fmt.Println(err)
return
}
inv, _ := oneimage.Apply(oneimage.NewImage(band), oneimage.Invert())
if err := w.WriteRows(inv.Frames[0].Image); err != nil {
fmt.Println(err)
return
}
bands++
}
w.Close()
back, _ := oneimage.DecodeBytes(out.Bytes())
r, g, b, _ := back.At(5, 7).RGBA()
fmt.Println(bands, r>>8, g>>8, b>>8)
}
Output: 4 250 248 127
func (*Source) Frame ¶
Frame returns frame i (0-based), decoding it, and the frames before it that compositing needs, when first asked. An index outside the file is an ErrOperation.
func (*Source) Image ¶
Image decodes every frame and returns the whole image: frames, loop count, metadata and the format's details.
func (*Source) Info ¶
Info returns what the file declares. Width, Height, FrameInfo and Metadata.Orientation are those of the pixels Source delivers: upright when the orientation is applied (the default).
func (*Source) Metadata ¶
Metadata returns the metadata blobs. With the orientation applied, the Orientation field is 1; the Exif block still holds the stored value, and Encode corrects it on output.
func (*Source) Region ¶
Region returns the rectangle r (in the coordinates of the delivered, upright pixels) of frame i as a new Pixmap with bounds at the origin. It equals the same rectangle cropped from the whole frame. A decoder that can decode a region (see CapRegion) is asked for just that part when the frame is not already decoded and no orientation has to be applied; otherwise the frame is decoded and kept, and the region copied from it. A rectangle that is empty or not inside the frame is an ErrOperation.
Example ¶
Region reads one rectangle without decoding the rest into memory.
package main
import (
"fmt"
"image"
"recursiveai.org/go/oneimage"
)
func gradientPNG(w, h int) []byte {
pm := oneimage.NewPixmap(image.Rect(0, 0, w, h), oneimage.RGB8)
for y := 0; y < h; y++ {
row := pm.Row8(y)
for x := 0; x < w; x++ {
row[3*x], row[3*x+1], row[3*x+2] = byte(x), byte(y), 128
}
}
data, _ := oneimage.EncodeBytes(pm, "png", nil)
return data
}
func main() {
src, _ := oneimage.Open(gradientPNG(64, 64), oneimage.WithAutoOrient(false))
part, _ := src.Region(0, image.Rect(10, 20, 14, 22))
fmt.Println(part.Bounds(), part.At(0, 0))
}
Output: (0,0)-(4,2) {10 20 128 255}
func (*Source) Release ¶
func (s *Source) Release()
Release drops the decoded pixels (and, for a Source opened on a ReaderAt, the compressed bytes); the next read decodes again. The facts from Open stay.
func (*Source) Thumbnail ¶
Thumbnail is the package function Thumbnail for an opened Source: it decodes at a reduced size where the format can, without keeping the decoded frames in the Source. The Source's context (OpenContext) stops it. The options are those of Thumbnail; WithLimits bounds the work, as the Source's own limits do not carry over.
type SourceChangedError ¶
type SourceChangedError struct {
// Err is what the check reported.
Err error
}
SourceChangedError is the error a Source returns when its change check fails. It matches ErrSourceChanged and ErrOperation.
func (*SourceChangedError) Error ¶
func (e *SourceChangedError) Error() string
Error describes the failed check.
func (*SourceChangedError) Is ¶
func (e *SourceChangedError) Is(target error) bool
Is reports a match with ErrSourceChanged and ErrOperation.
func (*SourceChangedError) Unwrap ¶
func (e *SourceChangedError) Unwrap() error
Unwrap exposes the check's own error.
type Statistics ¶
type Statistics struct {
// PixelCount is the number of pixels counted.
PixelCount int
// FullScale is the largest sample value: 255, or 65535 for 16-bit and
// float images.
FullScale float64
// Channels is ordered like [Histogram.Channels].
Channels []ChannelStats
}
Statistics is the per-channel summary of an image.
type Stop ¶
type Stop struct {
// Position is where along the gradient the colour sits, 0 at the start
// and 1 at the end.
Position float64
// Color is the colour at Position.
Color color.NRGBA
}
Stop is a colour at a position along a gradient.
type StrokeCap ¶
type StrokeCap uint8
StrokeCap is the shape of the open ends of a stroke and of every dash.
func (StrokeCap) MarshalText ¶
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (*StrokeCap) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type StrokeJoin ¶
type StrokeJoin uint8
StrokeJoin is the shape of a stroke's corners.
func (StrokeJoin) MarshalText ¶
func (v StrokeJoin) MarshalText() ([]byte, error)
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (StrokeJoin) String ¶
func (v StrokeJoin) String() string
String returns the lower-case name, or StrokeJoin(n) for an unknown value.
func (*StrokeJoin) UnmarshalText ¶
func (v *StrokeJoin) UnmarshalText(text []byte) error
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type TIFFCompression ¶
type TIFFCompression uint16
TIFF compression codes (tag 259) as the decoder reports them in TIFFPage.Compression and the encoder takes them in TIFFOptions.
const ( TIFFCompressionNone TIFFCompression = 1 // TIFFCompressionCCITTRLE is CCITT modified Huffman run-length coding // (read only). TIFFCompressionCCITTRLE TIFFCompression = 2 // TIFFCompressionGroup3 and TIFFCompressionGroup4 are CCITT T.4 and T.6 // fax coding (read only). TIFFCompressionGroup3 TIFFCompression = 3 TIFFCompressionGroup4 TIFFCompression = 4 TIFFCompressionLZW TIFFCompression = 5 // TIFFCompressionOldJPEG is the withdrawn TIFF 6.0 JPEG scheme, read on a // best-effort basis. TIFFCompressionOldJPEG TIFFCompression = 6 TIFFCompressionJPEG TIFFCompression = 7 // TIFFCompressionDeflate is zlib data under the Adobe code 8; // TIFFCompressionDeflateOld is the same data under the older code 32946. // The encoder writes code 8. TIFFCompressionDeflate TIFFCompression = 8 TIFFCompressionDeflateOld TIFFCompression = 32946 TIFFCompressionPackBits TIFFCompression = 32773 )
The compression schemes the library reads. The encoder writes the first four.
func (TIFFCompression) MarshalText ¶
func (v TIFFCompression) MarshalText() ([]byte, error)
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (TIFFCompression) String ¶
func (c TIFFCompression) String() string
String returns the name of the TIFFCompression, spelled as its text form and Parse function read it.
func (*TIFFCompression) UnmarshalText ¶
func (v *TIFFCompression) UnmarshalText(text []byte) error
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type TIFFInfo ¶
type TIFFInfo struct {
// BigTIFF reports the 64-bit container (version 43).
BigTIFF bool
// BigEndian reports byte order "MM".
BigEndian bool
// Pages has one entry per image file directory, in file order. Decode
// returns one frame per page.
Pages []TIFFPage
// Orientation is the first page's orientation.
Orientation int
}
TIFFInfo holds the facts a TIFF file states about itself, in Image.Details and Info.Details.
type TIFFOptions ¶
type TIFFOptions struct {
// Compression is [TIFFCompressionNone] (the zero value is also none),
// [TIFFCompressionLZW], [TIFFCompressionDeflate] or
// [TIFFCompressionPackBits]. Others are an [ErrUnsupported] error.
Compression TIFFCompression
// Predictor turns on differencing before LZW and Deflate: horizontal
// (predictor 2) for 8- and 16-bit samples, floating-point (3) for
// float32. It has no effect on other compressions and is not written
// for them.
Predictor bool
// DeflateLevel is the zlib level 1 to 9 for Deflate; 0 means 6.
DeflateLevel int
// RowsPerStrip is the number of rows in each strip. 0 chooses strips of
// roughly 64 KiB of raw data (at least one row). A value at or over the
// image height gives one strip.
RowsPerStrip int
// BigTIFF writes the 64-bit container instead of classic TIFF.
BigTIFF bool
// BigEndian writes byte order "MM" instead of "II".
BigEndian bool
// StripMetadata leaves out the ICC profile and XMP packet that would
// otherwise be carried over from the image.
StripMetadata bool
}
TIFFOptions configures the TIFF encoder. The zero value writes classic TIFF, uncompressed, one strip of about 8 KiB or more per page.
type TIFFPage ¶
type TIFFPage struct {
// Width and Height are the size in pixels.
Width, Height int
// Compression is the scheme tag 259 names.
Compression TIFFCompression
// Photometric is tag 262: 0 WhiteIsZero, 1 BlackIsZero, 2 RGB, 3
// palette, 5 separated (CMYK), 6 YCbCr.
Photometric int
// BitsPerSample and SamplesPerPixel are tags 258 and 277; a file whose
// samples differ in size is not read.
BitsPerSample, SamplesPerPixel int
// SampleFormat is tag 339: 1 unsigned integer, 3 floating point.
SampleFormat int
// Planar reports PlanarConfiguration 2: one plane per sample.
Planar bool
// Tiled reports tiles instead of strips; TileWidth and TileLength are
// then set, otherwise RowsPerStrip is (clamped to Height).
Tiled bool
// TileWidth and TileLength are the tile size in pixels when Tiled.
TileWidth, TileLength int
// RowsPerStrip is the strip height in pixels when not Tiled.
RowsPerStrip int
// Predictor is tag 317: 1 none, 2 horizontal differencing, 3
// floating-point differencing.
Predictor int
// Orientation is tag 274, 1 to 8; 1 when absent. Decoding never applies
// it; see [Orient].
Orientation int
// ExtraSamples is the first value of tag 338 when the file has one: 0
// unspecified, 1 associated alpha, 2 unassociated alpha; -1 when absent.
ExtraSamples int
// XResolution and YResolution are tags 282 and 283, ResolutionUnit tag
// 296 (1 none, 2 inch, 3 centimetre; 2 when absent). Zero when the file
// has none.
XResolution, YResolution float64
// ResolutionUnit is the unit of the resolutions: 1 none, 2 inch, 3
// centimetre.
ResolutionUnit int
}
TIFFPage holds what one image file directory states about its image. Decoding fills one per frame in TIFFInfo.Pages.
type TIFFWriter ¶
type TIFFWriter struct {
// contains filtered or unexported fields
}
TIFFWriter writes a TIFF file a band of rows at a time, one page after another, holding only the strip being filled (and the compressed strips of one batch), so an image taller than memory allows can be written as it is produced (for example from Source.Bands through a per-band operation).
Strips go to the destination as they complete; the directory of a page follows its strips (TIFF 6.0 section 2 lets directories sit anywhere), so the writer must go back and fill in the offset of each directory in the header or in the previous directory. That is why the destination is an io.WriteSeeker (an *os.File, for one): TIFF's first-directory offset sits at the start of the file and is not known until the first page's strips have been compressed. The destination must be positioned where the TIFF starts; offsets are relative to that point.
The pixel formats are those NewTIFFWriter lists. For the same pixels, options and metadata the bytes are exactly those EncodeTIFF writes for a Pixmap of the page's pixel format (or, for several pages, for an Image of such frames): the two share the strip, predictor, compression and directory code. Palette images and per-page resolution are not written (EncodeTIFF writes them for *image.Paletted frames and for TIFFInfo details).
Example ¶
A TIFF with two pages, each written a few rows at a time. The destination must be seekable, here a file.
package main
import (
"fmt"
"image"
"os"
"path/filepath"
"recursiveai.org/go/oneimage"
)
func main() {
dir, err := os.MkdirTemp("", "tiffwriter")
if err != nil {
fmt.Println(err)
return
}
defer os.RemoveAll(dir)
f, err := os.Create(filepath.Join(dir, "pages.tif"))
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
opts := &oneimage.TIFFOptions{Compression: oneimage.TIFFCompressionLZW}
tw, err := oneimage.NewTIFFWriter(f, 64, 40, oneimage.Gray8, opts, oneimage.Metadata{})
if err != nil {
fmt.Println(err)
return
}
page := oneimage.NewPixmap(image.Rect(0, 0, 64, 10), oneimage.Gray8)
for y := 0; y < 40; y += 10 { // four bands of ten rows
if err := tw.WriteRows(page); err != nil {
fmt.Println(err)
return
}
}
if err := tw.NextPage(16, 8, oneimage.RGB8); err != nil {
fmt.Println(err)
return
}
if err := tw.WriteRows(oneimage.NewPixmap(image.Rect(0, 0, 16, 8), oneimage.RGB8)); err != nil {
fmt.Println(err)
return
}
if err := tw.Close(); err != nil {
fmt.Println(err)
return
}
info, err := os.ReadFile(f.Name())
if err != nil {
fmt.Println(err)
return
}
img, err := oneimage.DecodeBytes(info)
if err != nil {
fmt.Println(err)
return
}
for _, fr := range img.Frames {
fmt.Println(fr.Image.Bounds().Dx(), fr.Image.Bounds().Dy())
}
}
Output: 64 40 16 8
func NewTIFFWriter ¶
func NewTIFFWriter(w io.WriteSeeker, width, height int, format PixelFormat, opts *TIFFOptions, meta Metadata) (*TIFFWriter, error)
NewTIFFWriter starts a TIFF file whose first page is width x height pixels of the given pixel format, and writes the file header. opts may be nil; it is read like TIFFOptions for EncodeTIFF. meta supplies the ICC profile, XMP packet and Exif block (written with the first page unless opts.StripMetadata) and the first page's orientation; it is written as given, so pass a block corrected with ExifForOutput when the size or orientation changed.
Formats: gray, RGB or CMYK with 8 or 16 bits or float32 samples (float16 is widened to float32), with or without alpha; straight alpha is written as an unassociated extra sample and premultiplied alpha as an associated one. Lab is an ErrUnsupported error. A strip holds RowsPerStrip rows (about 64 KiB by default), which is what the writer buffers; a RowsPerStrip as tall as the image makes the writer hold a whole page.
A LimitError is returned as soon as a classic (non-BigTIFF) file would pass 4 GiB: set opts.BigTIFF for larger files.
func (*TIFFWriter) Close ¶
func (t *TIFFWriter) Close() error
Close finishes the last page and the file. Fewer rows than a page's declared height is an error and leaves the output unfinished. It does not close the destination, and calling it again returns the first call's result.
func (*TIFFWriter) NextPage ¶
func (t *TIFFWriter) NextPage(width, height int, format PixelFormat) error
NextPage finishes the current page, which must have all its rows, and starts another of width x height pixels in the given pixel format. Pages may differ in size and format. The strip layout options apply to every page; metadata is written with the first page only.
func (*TIFFWriter) WriteBands ¶
WriteBands writes every band of seq into the current page with TIFFWriter.WriteRows; it does not close the writer, so `w.WriteBands(src.Bands(0, image.Rectangle{}, 0))` followed by TIFFWriter.Close copies a frame. For a file of several pages call WriteRows and NextPage between pages. It stops at the first error, which is returned (a band error from the sequence included).
type TaperCorner ¶
type TaperCorner uint8
TaperCorner says which end of the pulled-in edge moves.
const ( TaperBoth TaperCorner = iota TaperLeftOrTop TaperRightOrBottom )
Both ends move symmetrically; or only the left (or top) end; or only the right (or bottom) end.
func ParseTaperCorner ¶
func ParseTaperCorner(s string) (TaperCorner, error)
ParseTaperCorner reads "both", "left-or-top" or "right-or-bottom".
func (TaperCorner) MarshalText ¶
func (v TaperCorner) MarshalText() ([]byte, error)
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (TaperCorner) String ¶
func (c TaperCorner) String() string
String returns the name of the TaperCorner, spelled as its text form and Parse function read it.
func (*TaperCorner) UnmarshalText ¶
func (v *TaperCorner) UnmarshalText(text []byte) error
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type TaperSide ¶
type TaperSide uint8
TaperSide names the edge of a rectangle a taper pulls in.
func ParseTaperSide ¶
ParseTaperSide reads "top", "bottom", "left" or "right".
func (TaperSide) MarshalText ¶
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (TaperSide) String ¶
String returns the name of the TaperSide, spelled as its text form and Parse function read it.
func (*TaperSide) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type TextEntry ¶
type TextEntry struct {
// Keyword names the entry (1 to 79 Latin-1 characters in PNG).
Keyword string
// Text is the value, as UTF-8.
Text string
// Language and TranslatedKeyword are set by PNG iTXt entries.
Language, TranslatedKeyword string
// Compressed records that the entry was stored compressed (zTXt, or iTXt
// with its flag set); encoders keep that choice.
Compressed bool
// International marks an iTXt entry (UTF-8 with language tag) as opposed
// to Latin-1 tEXt or zTXt.
International bool
}
TextEntry is one keyword and text pair of a container that stores them.
type UnsupportedError ¶
type UnsupportedError struct {
// Format is the format involved, or empty when none applies.
Format string
// Feature names what is not supported, in plain words: "scaled decoding",
// "encoding xyz".
Feature string
// Err is the underlying error, such as an unsupported-feature error of a
// reader this library sits on; nil when there is none. [errors.Is] and
// [errors.As] look through it.
Err error
}
UnsupportedError describes a valid but unsupported feature. It matches ErrUnsupported.
func (*UnsupportedError) Error ¶
func (e *UnsupportedError) Error() string
Error describes the unsupported feature.
func (*UnsupportedError) Is ¶
func (e *UnsupportedError) Is(target error) bool
Is reports a match with ErrUnsupported.
func (*UnsupportedError) Unwrap ¶
func (e *UnsupportedError) Unwrap() error
Unwrap returns the underlying error, if any.
type Vec2 ¶
type Vec2 struct {
// X is the horizontal coordinate, growing to the right.
X float64
// Y is the vertical coordinate, growing downwards.
Y float64
}
Vec2 is a point or vector with fractional coordinates, in pixels unless a function says otherwise. Every float point in the library is a Vec2.
type WebPExact ¶
type WebPExact uint8
WebPExact says whether the colour of fully transparent pixels is kept.
const ( // WebPExactDefault keeps it for lossless output and lets lossy output // replace it. WebPExactDefault WebPExact = iota // WebPExactOn keeps the colour of fully transparent pixels. WebPExactOn // WebPExactOff lets the encoder replace the colour of fully transparent // pixels with whatever compresses best. WebPExactOff )
func (WebPExact) MarshalText ¶
MarshalText implements encoding.TextMarshaler. It fails for an unknown value; otherwise it is the name String returns.
func (*WebPExact) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler; names are compared ignoring ASCII case.
type WebPInfo ¶
type WebPInfo struct {
// Lossless is true when every frame is VP8L.
Lossless bool
// Animated is true when the file has the animation flag.
Animated bool
// Background is the ANIM chunk's background colour. Decoding does not
// use it: frames are composed on a transparent canvas, as libwebp's
// animation decoder does.
Background color.NRGBA
}
WebPInfo is what a decoded WebP image reports in Image.Details and Info.Details.
type WebPOptions ¶
type WebPOptions struct {
// Lossless writes VP8L (bit-exact) instead of VP8.
Lossless bool
// Quality is the lossy quality 1 to 100 (0 means 75; WebPOff means 0). For
// lossless output it is ignored: the result is always exact.
Quality int
// Effort is the search effort 1 to 6 (0 means 4; WebPOff means 0). Higher
// efforts try more modes and configurations and give smaller files.
Effort int
// Exact controls the colour under fully transparent pixels.
Exact WebPExact
// FilterStrength is the lossy loop filter strength 1 to 100. 0 picks the
// strength that gives the best PSNR; WebPOff turns the filter off.
FilterStrength int
// FilterSharpness is the lossy loop filter sharpness 0 to 7.
FilterSharpness int
// Segments is the number of lossy quantizer segments, 1 to 4 (0 means 4).
Segments int
// SNS is the strength 1 to 100 with which segments differ in quantizer
// (0 means 50; WebPOff means 0, which makes every macroblock use the same
// quantizer).
SNS int
// StripMetadata leaves out the ICC profile, Exif and XMP of the image.
StripMetadata bool
}
WebPOptions configures the WebP encoder. The zero value gives lossy output at quality 75 and effort 4.
Example ¶
package main
import (
"bytes"
"fmt"
"image"
"recursiveai.org/go/oneimage"
)
func main() {
src := image.NewNRGBA(image.Rect(0, 0, 16, 16))
var small, large bytes.Buffer
// Quality runs from 1 to 100; the zero value means 75 and oneimage.WebPOff
// stands for an explicit 0.
oneimage.EncodeWebP(&small, src, &oneimage.WebPOptions{Quality: oneimage.WebPOff})
oneimage.EncodeWebP(&large, src, &oneimage.WebPOptions{Quality: 100})
fmt.Println(small.Len() <= large.Len())
}
Output: true
Source Files
¶
- analysis.go
- blend.go
- bmp_decode.go
- bmp_encode.go
- bmp_writer.go
- brush.go
- brush_gradient.go
- color_convert.go
- color_model.go
- color_profile.go
- composite.go
- convert.go
- core_anim.go
- core_context.go
- core_exif.go
- core_extra.go
- core_metaconv.go
- core_metadata.go
- core_pixels.go
- core_registry.go
- core_source.go
- core_stream.go
- dither.go
- dither_op.go
- doc.go
- draw.go
- draw_blend.go
- draw_edit.go
- draw_pen.go
- draw_pixels.go
- effects.go
- enum_text.go
- errors.go
- filter_core.go
- filter_ops.go
- geometry.go
- geometry_transform.go
- gif.go
- gif_decode.go
- gif_encode.go
- ico_codec.go
- image.go
- jpeg.go
- jpeg_arith.go
- jpeg_dct.go
- jpeg_decode.go
- jpeg_encode.go
- jpeg_huff.go
- jpeg_out.go
- jpeg_restart.go
- jpeg_scan.go
- jpeg_stream.go
- jpeg_tables.go
- jpeg_writer.go
- limits.go
- matrix.go
- op.go
- op_reads.go
- ops_options.go
- options.go
- orient.go
- path.go
- path_boolean.go
- pixel.go
- pixel_formats.go
- pixmap.go
- png.go
- png_decode.go
- png_encode.go
- png_parse.go
- png_stream.go
- png_writer.go
- registry.go
- render_size.go
- resize.go
- resize_engine.go
- rgba.go
- thumbnail.go
- tiff.go
- tiff_codec.go
- tiff_conv.go
- tiff_decode.go
- tiff_encode.go
- tiff_ifd.go
- tiff_read.go
- tiff_stream.go
- tiff_writer.go
- tone_auto.go
- tone_color.go
- tone_core.go
- tone_ops.go
- webp.go
- webp_encode.go
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
blend
Package blend is the per-pixel blend and Porter-Duff kernel shared by the compositing operations, the drawing engine and layers.
|
Package blend is the per-pixel blend and Porter-Duff kernel shared by the compositing operations, the drawing engine and layers. |
|
boolean
Package boolean computes unions, intersections, differences and exclusive ors of regions bounded by polygons, exactly on a fixed grid.
|
Package boolean computes unions, intersections, differences and exclusive ors of regions bounded by polygons, exactly on a fixed grid. |
|
brotli
Package brotli decodes Brotli streams (RFC 7932).
|
Package brotli decodes Brotli streams (RFC 7932). |
|
ccitt
Package ccitt decodes the bilevel fax codings TIFF uses: the modified Huffman run-length coding (TIFF 6.0 section 10), Group 3 one- and two-dimensional coding (ITU-T T.4) and Group 4 (ITU-T T.6).
|
Package ccitt decodes the bilevel fax codings TIFF uses: the modified Huffman run-length coding (TIFF 6.0 section 10), Group 3 one- and two-dimensional coding (ITU-T T.4) and Group 4 (ITU-T T.6). |
|
doccheck
Package doccheck finds exported identifiers without a doc comment.
|
Package doccheck finds exported identifiers without a doc comment. |
|
enumtext
Package enumtext implements the text forms of the library's enumerations from their String methods, so every enum works with encoding.TextMarshaler and encoding.TextUnmarshaler in the same way.
|
Package enumtext implements the text forms of the library's enumerations from their String methods, so every enum works with encoding.TextMarshaler and encoding.TextUnmarshaler in the same way. |
|
flate
Package flate is oneimage's own DEFLATE (RFC 1951) and zlib (RFC 1950) implementation.
|
Package flate is oneimage's own DEFLATE (RFC 1951) and zlib (RFC 1950) implementation. |
|
geom
Package geom holds the geometry the drawing engine builds on: paths of lines and Bézier curves, SVG path data, shape factories, flattening and the stroker.
|
Package geom holds the geometry the drawing engine builds on: paths of lines and Bézier curves, SVG path data, shape factories, flattening and the stroker. |
|
jbig2
Package jbig2 decodes JBIG2 bilevel images (ITU-T T.88), the codec scanned PDF pages use.
|
Package jbig2 decodes JBIG2 bilevel images (ITU-T T.88), the codec scanned PDF pages use. |
|
jpx
Package jpx decodes JPEG 2000 Part 1 images (ITU-T T.800), the codec PDF files use for /JPXDecode.
|
Package jpx decodes JPEG 2000 Part 1 images (ITU-T T.800), the codec PDF files use for /JPXDecode. |
|
lzw
Package lzw implements the variable-width LZW coding that GIF uses (GIF89a appendix F), in a form TIFF's variants can reuse: codes are packed least-significant-bit first or most-significant-bit first, and the code width grows either when the table fills (GIF) or one code earlier (TIFF's "early change").
|
Package lzw implements the variable-width LZW coding that GIF uses (GIF89a appendix F), in a form TIFF's variants can reuse: codes are packed least-significant-bit first or most-significant-bit first, and the code width grows either when the table fills (GIF) or one code earlier (TIFF's "early change"). |
|
par
Package par runs independent ranges of work on several goroutines.
|
Package par runs independent ranges of work on several goroutines. |
|
quant
Package quant reduces RGBA images to a palette of at most 256 colours.
|
Package quant reduces RGBA images to a palette of at most 256 colours. |
|
raster
Package raster turns flattened outlines into coverage: exact-area anti-aliased coverage (the signed-area accumulation method) or the pixel-centre inside test, with the non-zero and even-odd rules.
|
Package raster turns flattened outlines into coverage: exact-area anti-aliased coverage (the signed-area accumulation method) or the pixel-centre inside test, with the non-zero and even-odd rules. |
|
resample
Package resample builds the weight tables that separable resampling uses.
|
Package resample builds the weight tables that separable resampling uses. |
|
shape
Package shape holds the pieces of drawing a filled or stroked shape that do not depend on the pixmap: turning a path into the merged outline that is rasterised, and the arithmetic that lays a solid colour over 8-bit pixels.
|
Package shape holds the pieces of drawing a filled or stroked shape that do not depend on the pixmap: turning a path into the merged outline that is rasterised, and the arithmetic that lays a solid colour over 8-bit pixels. |
|
vp8
Package vp8 implements the VP8 key-frame codec used by lossy WebP (RFC 6386): a decoder to planar YUV 4:2:0 and an encoder from it.
|
Package vp8 implements the VP8 key-frame codec used by lossy WebP (RFC 6386): a decoder to planar YUV 4:2:0 and an encoder from it. |
|
vp8l
Package vp8l implements the WebP lossless bitstream (RFC 9649 section 3): a decoder and an encoder over ARGB pixels.
|
Package vp8l implements the WebP lossless bitstream (RFC 9649 section 3): a decoder and an encoder over ARGB pixels. |
|
woff
Package woff unpacks WOFF 1.0 and WOFF 2.0 web fonts into the plain sfnt (or TrueType Collection) bytes a font parser reads.
|
Package woff unpacks WOFF 1.0 and WOFF 2.0 web fonts into the plain sfnt (or TrueType Collection) bytes a font parser reads. |
|
Package layers is the layered-document model: a Document holds a tree of pixel, group, fill and adjustment layers with opacity, blend modes, masks, clipping and Photoshop-style layer styles, and renders them to a oneimage.Pixmap on demand, tile by tile, so a change recomputes only the tiles it touches.
|
Package layers is the layered-document model: a Document holds a tree of pixel, group, fill and adjustment layers with opacity, blend modes, masks, clipping and Photoshop-style layer styles, and renders them to a oneimage.Pixmap on demand, tile by tile, so a change recomputes only the tiles it touches. |
|
Package metafile reads Windows metafiles: EMF ([MS-EMF]), EMF+ ([MS-EMFPLUS], both dual files and EMF+ only) and WMF ([MS-WMF]), including placeable WMF and an EMF embedded in a WMF.
|
Package metafile reads Windows metafiles: EMF ([MS-EMF]), EMF+ ([MS-EMFPLUS], both dual files and EMF+ only) and WMF ([MS-WMF]), including placeable WMF and an EMF embedded in a WMF. |
|
Package pdf draws PDF pages as oneimage rasters.
|
Package pdf draws PDF pages as oneimage rasters. |
|
Package psd reads and writes Photoshop documents (PSD, and PSB with its 8-byte lengths).
|
Package psd reads and writes Photoshop documents (PSD, and PSB with its 8-byte lengths). |
|
Package stdreg registers oneimage's decoders with the standard library's image package.
|
Package stdreg registers oneimage's decoders with the standard library's image package. |
|
Package svg renders SVG documents to pixels, written for oneimage.
|
Package svg renders SVG documents to pixels, written for oneimage. |
|
Package text draws and measures rich text: fonts, shaping, layout and painting, with the pixel and path types of package oneimage.
|
Package text draws and measures rich text: fonts, shaping, layout and painting, with the pixel and path types of package oneimage. |
|
Package web serves resized, converted and recompressed images over HTTP, driven by commands in the URL's query string, and caches the results.
|
Package web serves resized, converted and recompressed images over HTTP, driven by commands in the URL's query string, and caches the results. |