imagequant

package module
Version: v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 7, 2018 License: BSD-2-Clause Imports: 6 Imported by: 1

README

go-imagequant

GoDoc

About

libimagequant is a small, portable C library for high-quality conversion of RGBA images to 8-bit indexed-color (palette) images.

This project provides Go bindings for libimagequant. The bindings were adapted to be closer to Go code conventions. As a result, C memory management details were reduced to a single, optional, Release() call, and pixel data can be transferred by using Go's Image interface.

Building

go-imagequant uses the system version of the static libimagequant library. More information about how to build libimagequant can be found on the libimagequant project page.

go-imagequant package path is currently github.com/InfinityTools/imagequant. The bindings can be built via go build.

This package makes use of CGO, which requires a decent C compiler to be installed. However, using go install removes the C compiler requirement for future invocations of go build.

Overview

The basic flow is:

  1. Create an Attributes structure.
  2. Create an Image structure from a Go image.Image object or a Histogram structure.
  3. Perform quantization from the Image or Histogram structure (generate palette).
  4. Request a paletted Go Image object.

Basic example (full code can be found in example/example.go):

package main

import "github.com/InfinityTools/go-imagequant"

func main() {
  att := imagequant.CreateAttributes()
  defer att.Release()

  // imgIn is expected to be a valid image.Image object.
  qimg := att.CreateImage(imgIn, 0.0)

  qresult, _ := att.QuantizeImage(qimg)

  // imgOut is a paletted Go image that can be directly exported using Go's image export packages.
  imgOut, _ := att.WriteRemappedImage(qresult, qimg)
}

Detailed function descriptions can be found in the respective Go source files.

Documentation

For docs, see https://godoc.org/github.com/InfinityTools/go-imagequant .

License

go-imagequant is released under the BSD 2-clause license. See LICENSE for more details.

libimagequant itself is available under under the GPL v3 or later license and a commercial license for non-GPL software. See libimagequant-license.txt for more details.

Documentation

Overview

Package imagequant provides bindings to the external imagequant C library.

Original C library: https://github.com/ImageOptim/libimagequant/

Index

Constants

View Source
const (
	SPEED_SLOWEST = 1
	SPEED_DEFAULT = 3
	SPEED_FASTEST = 10
)
View Source
const (
	QUALITY_BEST  = 100
	QUALITY_GOOD  = 80
	QUALITY_WORST = 0
)
View Source
const (
	DITHER_MIN = 0.0
	DITHER_MAX = 1.0
)

Variables

View Source
var (
	// Potential error codes
	ErrQualityTooLow      = errors.New("Quality too low")
	ErrValueOutOfRange    = errors.New("Value is out of range")
	ErrOutOfMemory        = errors.New("Out of memory")
	ErrAborted            = errors.New("Aborted")
	ErrBitmapNotAvailable = errors.New("Bitmap is not available")
	ErrBufferTooSmall     = errors.New("Buffer is too small")
	ErrInvalidPointer     = errors.New("Invalid pointer")
	ErrUnsupported        = errors.New("Unsupported")
	ErrUnknown            = errors.New("Unknown error")
)

Functions

func GetVersion

func GetVersion() (major, minor, patch int)

GetVersion returns the imagequant library version as major, minor and patch number.

func GetVersionString

func GetVersionString() string

GetVersionString returns the imagequant library version as a preformatted string.

func NRGBA

func NRGBA(col color.Color) (r, g, b, a byte)

NRGBA converts a premultiplied color back to a normalized color with each component in range [0, 255].

Types

type Attributes

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

The Attributes struct is used to call the majority of quantization functions. This is the only structure that can be released manually.

func CreateAttributes

func CreateAttributes() *Attributes

Returns an object that will hold initial settings (attributes) for the library.

IMPORTANT: The object must be freed by Release after it is no longer needed.

func (*Attributes) AddColorsToHistogram

func (att *Attributes) AddColorsToHistogram(hist *Histogram, entries []HistogramEntry, gamma float64) error

Alternative to AddImageToHistogram. Instead of counting colors in an image, it directly takes an array of colors and their counts.

This function is only useful if you already have a histogram of the image from another source.

func (*Attributes) AddImageFixedColor

func (att *Attributes) AddImageFixedColor(img *Image, col color.Color) error

Reserves a color in the output palette created from this image.

It behaves as if the given color was used in the image and was very important. RGB values of the Color object are assumed to have the same gamma as the image. It must be called before the image is quantized.

Returns error if more than 256 colors are added. If image is quantized to fewer colors than the number of fixed colors added, then excess fixed colors will be ignored.

func (*Attributes) AddImageToHistogram

func (att *Attributes) AddImageToHistogram(hist *Histogram, img *Image) error

"Learns" colors from the image, which will be later used to generate the palette.

After the image is added to the histogram it may be freed to save memory (but it's more efficient to keep the image object around if it's going to be used for remapping). Fixed colors added to the image are also added to the histogram. If total number of fixed colors exceeds 256, this function will fail with ErrBufferTooSmall.

func (*Attributes) CopyAttribute

func (att *Attributes) CopyAttribute() *Attributes

Creates an independent copy of the calling object.

IMPORTANT: The copy must also be freed by the Release function.

func (*Attributes) CreateHistogram

func (att *Attributes) CreateHistogram() *Histogram

Creates a histogram object that will be used to collect color statistics from multiple images.

func (*Attributes) CreateImage

func (att *Attributes) CreateImage(img image.Image, gamma float64) *Image

Same as CreateImageBuffer, but takes a Go Image interface as source.

func (*Attributes) CreateImageBuffer

func (att *Attributes) CreateImageBuffer(rgba []byte, width, height int, gamma float64) *Image

Creates an object that represents the image pixels to be used for quantization and remapping.

The pixel array must be contiguous run of RGBA pixels (alpha is the last component, 0 = transparent, 255 = opaque).

The rgba array must not be modified or freed until this object is freed with liq_image_destroy. See also liq_image_set_memory_ownership.

width and height are dimensions in pixels. An image 10x10 pixel large will need a 400-byte array.

gamma can be 0 for images with the typical 1/2.2 gamma. Otherwise gamma must be > 0 and < 1, e.g. 0.45455 (1/2.2) or 0.55555 (1/1.8).

Generated palette will use the same gamma unless SetOutputGamma is used. If SetOutputGamma is not used, then it only affects whether brighter or darker areas of the image will get more palette colors allocated.

Returns nil on failure, e.g. if rgba is nil or too small or width/height is <= 0.

func (*Attributes) CreateImageBufferRows

func (att *Attributes) CreateImageBufferRows(rgbaRows [][]byte, width, height int, gamma float64) *Image

Same as CreateImageBuffer, but takes an array of rows of pixels.

This allows defining images with reversed rows (like in BMP), "stride" different than width or using only fragment of a larger bitmap, etc. The rows array must have at least height elements, and each row must be at least width RGBA pixels wide.

func (*Attributes) GetImageHeight

func (att *Attributes) GetImageHeight(img *Image) int

Getter for image height.

func (*Attributes) GetImageWidth

func (att *Attributes) GetImageWidth(img *Image) int

Getter for image width.

func (*Attributes) GetMaxColors

func (att *Attributes) GetMaxColors() int

Returns the value set by SetMaxColors.

func (*Attributes) GetMinPosterization

func (att *Attributes) GetMinPosterization() int

Returns the value set by SetMinPosterization.

func (*Attributes) GetOutputGamma

func (att *Attributes) GetOutputGamma(res *Result) float64

Returns the gamma value for the output image.

func (*Attributes) GetPalette

func (att *Attributes) GetPalette(res *Result) color.Palette

Returns a palette optimized for the image that has been quantized or remapped (final refinements are applied to the palette during remapping).

It's valid to call this method before remapping, if you don't plan to remap any images or want to use same palette for multiple images. Returns a Palette object with 0 color entries on error.

func (*Attributes) GetQuality

func (att *Attributes) GetQuality() (min, max int)

Returns the minimum/maximum range of quality set by SetQuality.

func (*Attributes) GetQuantizationError

func (att *Attributes) GetQuantizationError(res *Result) float64

Returns mean square error of quantization (square of difference between pixel values in the source image and its remapped version).

Alpha channel, gamma correction and approximate importance of pixels is taken into account, so the result isn't exactly the mean square error of all channels. or most images MSE 1-5 is excellent. 7-10 is OK. 20-30 will have noticeable errors. 100 is awful.

This function may return -1 if the value is not available (this happens when a high speed has been requested, the image hasn't been remapped yet, and quality limit hasn't been set, see SetSpeed and SetQuality). The value is not updated when multiple images are remapped, it applies only to the image used in QuantizeImage or the first image that has been remapped. See GetRemappingError.

func (*Attributes) GetQuantizationQuality

func (att *Attributes) GetQuantizationQuality(res *Result) int

Analoguous to GetQuantizationError, but returns quantization error as quality value in the same 0-100 range that is used by SetQuality.

It may return -1 if the value is not available (see note in GetQuantizationError).

func (*Attributes) GetRemappingError

func (att *Attributes) GetRemappingError(res *Result) float64

Returns mean square error of last remapping done (square of difference between pixel values in the remapped image and its remapped version).

Alpha channel and gamma correction are taken into account, so the result isn't exactly the mean square error of all channels.

func (*Attributes) GetRemappingQuality

func (att *Attributes) GetRemappingQuality(res *Result) int

Analoguous to GetRemappingError, but returns quantization error as quality value in the same 0-100 range that is used by SetQuality.

func (*Attributes) GetSpeed

func (att *Attributes) GetSpeed() int

Returns the value set by SetSpeed.

func (*Attributes) QuantizeHistogram

func (att *Attributes) QuantizeHistogram(hist *Histogram) (res *Result, err error)

Generates a palette from the histogram. On success returns the fully initialized Result object.

func (*Attributes) QuantizeImage

func (att *Attributes) QuantizeImage(img *Image) (res *Result, err error)

Performs quantization (palette generation) based on current Quantizer settings and pixels of the image.

Returns the Result object if quantization succeeds. Error returns ErrQualityTooLow if quantization fails due to limit set in SetQuality.

func (*Attributes) Release

func (att *Attributes) Release()

Call this function to manually release the attributes. Otherwise, Golang's own garbage collector will take care of it eventually.

func (*Attributes) SetDitheringLevel

func (att *Attributes) SetDitheringLevel(res *Result, ditherLevel float32) error

Enables/disables dithering in WriteRemappedImage.

Dithering level must be between 0 and 1 (inclusive). Dithering level 0 enables fast non-dithered remapping. Otherwise a variation of Floyd-Steinberg error diffusion is used.

func (*Attributes) SetImageBackground

func (att *Attributes) SetImageBackground(img *Image, background *Image) error

Analyze and remap this image with assumption that it will be always presented exactly on top of this background.

When this image is remapped to a palette with a fully transparent color (use AddImageFixedColor to ensure this) pixels that are better represented by the background than the palette will be made transparent. This function can be used to improve quality of animated GIFs by setting previous animation frame as the background.

Returns ErrBufferTooSmall if the background image has a different size than the foreground.

func (*Attributes) SetImageImportanceMap

func (att *Attributes) SetImageImportanceMap(img *Image, importanceMap []byte) error

Importance map controls which areas of the image get more palette colors.

Pixels corresponding to 0 values in the map are completely ignored. The higher the value the more weight is placed on the given pixel, giving it higher chance of influencing the final palette. The map is one byte per pixel and must have the same size as the image (width×height bytes).

Returns ErrInvalidPointer if any pointer is nil and ErrBufferTooSmall if the map size does not match the image size.

func (*Attributes) SetLastIndexTransparent

func (att *Attributes) SetLastIndexTransparent(set bool)

Setting to false makes alpha colors sorted before opaque colors. "true" mixes colors together except completely transparent color, which is moved to the end of the palette. This is a workaround for programs that blindly assume the last palette entry is transparent.

func (*Attributes) SetMaxColors

func (att *Attributes) SetMaxColors(colors int) error

Specifies the maximum number of colors to use. The default is 256.

Instead of setting a fixed limit it's better to use SetQuality. Returns ErrValueOutOfRange if number of colors is outside the range 2-256.

func (*Attributes) SetMinPosterization

func (att *Attributes) SetMinPosterization(bits int) error

Ignores the given number of least significant bits in all channels, posterizing image to 2^bits levels.

0 gives full quality. Use 2 for VGA or 16-bit RGB565 displays, 4 if image is going to be output on a RGB444/RGBA4444 display (e.g. low-quality textures on Android).

Returns LIQ_VALUE_OUT_OF_RANGE if the value is outside the 0-4 range.

func (*Attributes) SetOutputGamma

func (att *Attributes) SetOutputGamma(res *Result, gamma float64) error

Sets gamma correction for generated palette and remapped image.

Must be > 0 and < 1, e.g. 0.45455 for gamma 1/2.2 in PNG images. By default output gamma is same as gamma of the input image.

func (*Attributes) SetQuality

func (att *Attributes) SetQuality(min, max int) error

Quality is in range 0 (worst) to 100 (best) and values are analoguous to JPEG quality (i.e. 80 is usually good enough).

Quantization will attempt to use the lowest number of colors needed to achieve maximum quality. max value of 100 is the default and means conversion as good as possible. If it's not possible to convert the image with at least minimum quality (i.e. 256 colors is not enough to meet the minimum quality), then liq_image_quantize will fail. The default minimum is 0 (proceeds regardless of quality).

Quality measures how well the generated palette fits image given to liq_image_quantize. If a different image is remapped with WriteRemappedImage, then actual quality may be different. Regardless of the quality settings the number of colors won't exceed the maximum (see SetMaxColors). The range of QUALITY_xxx constants covers the common uses.

Returns ErrValueOutOfRange if target is lower than minimum or any of them is outside the 0-100 range. Returns ErrInvalidPointer if attr appears to be invalid.

func (*Attributes) SetSpeed

func (att *Attributes) SetSpeed(speed int) error

Higher speed levels disable expensive algorithms and reduce quantization precision. The default speed is 3.

Speed 1 gives marginally better quality at significant CPU cost. Speed 10 has usually 5% lower quality, but is 8 times faster than the default. High speeds combined with SetQuality will use more colors than necessary and will be less likely to meet minimum required quality. The range of SPEED_xxx constants covers the common uses. Features dependent on speed:

Noise-sensitive dithering speed     1 to 5
Forced posterization                8-10 or if image has more than million colors
Quantization error known            1-7 or if minimum quality is set
Additional quantization techniques  1-6

Returns ErrValueOutOfRange if the speed is outside the 1-10 range.

func (*Attributes) WriteRemappedImage

func (att *Attributes) WriteRemappedImage(res *Result, img *Image) (imgOut image.Image, err error)

A convenience function that returns a paletted Go Image object.

func (*Attributes) WriteRemappedImageBuffer

func (att *Attributes) WriteRemappedImageBuffer(res *Result, img *Image) (buf []byte, err error)

Remaps the image to palette and returns the converted image as a byte array, 1 pixel per byte.

For best performance call GetPalette after this function, as palette is improved during remapping (except when QuantizeHistogram is used).

The returned byte array is assumed to be contiguous, with rows ordered from top to bottom, and no gaps between rows. If you need to return a sequence of rows with padding or upside-down order, then use WriteRemappedImageRows.

func (*Attributes) WriteRemappedImageBufferRows

func (att *Attributes) WriteRemappedImageBufferRows(res *Result, img *Image, rows [][]byte) (rowsOut [][]byte, err error)

Similar to WriteRemappedImageBuffer. Returns a remapped image, at 1 byte per pixel, to each row pointed by rows multi-array.

The array must have at least as many elements as height of the image, and each row must have at least as many bytes as width of the image. Rows must not overlap.

type Histogram

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

Histogram struct is required by several functions. Don't accss the content directly.

type HistogramEntry

type HistogramEntry struct {
	Color color.Color // The color value definition
	Count uint        // Number of occurrence, influences the weight or importance of the color.
}

A HistogramEntry holds usage information of a single color value.

type Image

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

Image struct is required by several functions. Don't access the content directly.

type Result

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

Result struct is required by several functions. Don't access the content directly.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto
y or Y : Canonical URL