### Loading Image in JavaScript (Browser)
Source: https://github.com/ibezkrovnyi/image-quantization/blob/main/packages/image-q/API-README.md
Provides a basic JavaScript example for loading an image in a web browser. It uses an `
` element and its `onload` event to execute code once the image has finished loading from a specified URL.
```javascript
var img = document.createElement("img");
img.onload = function() {
// image is loaded, here should be all code utilizing image
...
}
img.src = "http://pixabay.com/static/uploads/photo/2012/04/11/11/32/letter-a-27580_640.png"
```
--------------------------------
### Generator-based Palette Quantization with WuQuant
Source: https://github.com/ibezkrovnyi/image-quantization/blob/main/packages/image-q/API-README.md
Illustrates two methods for asynchronous palette quantization using generators. The first example shows iterative progress tracking, while the second demonstrates a concise way to get the final palette using `Array.from`.
```ts
// example 1
const paletteQuantizer = new WuQuant(distanceCalculator, 256);
paletteQuantizer.sample(pointContainer1);
paletteQuantizer.sample(pointContainer2);
const generator = paletteQuantizer.quantize();
let palette;
while (true) {
// calling to generator.next() may be easily wrapped with setTimeout to make it async
const result = generator.next();
if (result.done) break;
if (result.value.palette) palette = result.palette;
console.log(`${result.value.progress}% done`);
}
// example 2
const paletteQuantizer = new WuQuant(distanceCalculator, 256);
paletteQuantizer.sample(pointContainer1);
paletteQuantizer.sample(pointContainer2);
const palette = Array.from(paletteQuantizer.quantize()).pop().palette;
```
--------------------------------
### Generator-based Image Quantization with ErrorDiffusionArray
Source: https://github.com/ibezkrovnyi/image-quantization/blob/main/packages/image-q/API-README.md
Illustrates two approaches for asynchronous image quantization using generators. The first example demonstrates step-by-step progress tracking, while the second provides a compact way to obtain the final output point container.
```ts
// example 1
const imageQuantizer = new ErrorDiffusionArray(
distanceCalculator,
ErrorDiffusionArrayKernel.Jarvis,
);
const generator = imageQuantizer.quantize(inPointContainer, palette);
let outPointContainer;
while (true) {
// calling to generator.next() may be easily wrapped with setTimeout to make it async
const result = generator.next();
if (result.done) break;
if (result.value.pointContainer) outPointContainer = result.pointContainer;
console.log(`${result.value.progress}% done`);
}
// example 2
const imageQuantizer = new ErrorDiffusionArray(
distanceCalculator,
ErrorDiffusionArrayKernel.Jarvis,
);
const outPointContainer = Array.from(
imageQuantizer.quantize(inPointContainer, palette),
).pop().pointContainer;
```
--------------------------------
### Synchronous Palette Quantization with WuQuant
Source: https://github.com/ibezkrovnyi/image-quantization/blob/main/packages/image-q/API-README.md
Demonstrates how to use a `WuQuant` palette quantizer synchronously. It samples multiple point containers and then quantizes them to generate a palette.
```ts
const paletteQuantizer = new WuQuant(distanceCalculator, 256);
paletteQuantizer.sample(pointContainer1);
paletteQuantizer.sample(pointContainer2);
const palette = paletteQuantizer.quantizeSync();
```
--------------------------------
### Instantiating a BT.709 Euclidean Color Distance Calculator
Source: https://github.com/ibezkrovnyi/image-quantization/blob/main/packages/image-q/API-README.md
Shows how to create an instance of the EuclideanBT709 class, which calculates color distance using BT.709 sRGB coefficients.
```typescript
const distanceCalculator = new EuclideanBT709();
```
--------------------------------
### Import image-q as CommonJS Module
Source: https://github.com/ibezkrovnyi/image-quantization/blob/main/README.md
This snippet shows how to require the `image-q` library using CommonJS syntax, typically used in Node.js environments.
```javascript
var iq = require('image-q');
```
--------------------------------
### image-q API Features Overview
Source: https://github.com/ibezkrovnyi/image-quantization/blob/main/README.md
This section outlines the key features and capabilities of the `image-q` library's API, including supported input types, various color distance algorithms, different palette and image quantization methods, and available output formats.
```APIDOC
API:
Basic API: sync and promise-based async
Advanced API: sync and generator-based
Import Supported Types:
HTMLImageElement
HTMLCanvasElement
NodeCanvas
ImageData
Array
CanvasPixelArray
Uint8Array
Uint32Array
Color Distance Algorithms:
Euclidean: 1/1/1/1 coefficients (originally used in Xiaolin Wu's Quantizer WuQuant)
EuclideanBT709NoAlpha: BT.709 sRGB coefficients (originally used in RGBQuant)
EuclideanBT709: BT.709 sRGB coefficients + alpha support
Manhattan: 1/1/1/1 coefficients (originally used in NeuQuant)
ManhattanBT709: BT.709 sRGB coefficients
ManhattanNommyde: see https://github.com/igor-bezkrovny/image-quantization/issues/4#issuecomment-234527620
CIEDE2000: CIEDE2000 (very slow)
CIE94Textiles: CIE94 implementation for textiles
CIE94GraphicArts: CIE94 implementation for graphic arts
CMetric: see http://www.compuphase.com/cmetric.htm
PNGQuant: used in pngQuant tool
Palette Quantizers:
NeuQuant: (original code ported, integer calculations)
NeuQuantFloat: (floating-point calculations)
RGBQuant
WuQuant
Image Quantizers:
NearestColor
ErrorDiffusionArray: two modes of error propagation are supported: xnview and gimp
FloydSteinberg
FalseFloydSteinberg
Stucki
Atkinson
Jarvis
Burkes
Sierra
TwoSierra
SierraLite
ErrorDiffusionRiemersma: Hilbert space-filling curve is used
Output Formats:
Uint32Array
Uint8Array
```
--------------------------------
### Build Color Palette from Image Data (Async and Sync)
Source: https://github.com/ibezkrovnyi/image-quantization/blob/main/packages/image-q/API-README.md
This API allows building a color palette from sample images, returning a `Palette` instance. It provides both asynchronous (Promise-based) and synchronous methods. Optional parameters include the color distance formula, palette quantization algorithm, and the desired number of colors. The asynchronous version also supports a progress callback.
```ts
import { buildPalette } from 'image-q'; // or const buildPalette = require('image-q').buildPalette
const palette = await buildPalette([pointContainer], {
colorDistanceFormula: 'euclidean', // optional
paletteQuantization: 'neuquant', // optional
colors: 128, // optional
onProgress: (progress) => console.log('applyPalette', progress), // optional
});
```
```ts
import { buildPaletteSync } from 'image-q'; // or const buildPaletteSync = require('image-q').buildPaletteSync
const palette = buildPaletteSync([pointContainer], {
colorDistanceFormula: 'euclidean', // optional
paletteQuantization: 'neuquant', // optional
colors: 128, // optional
});
```
--------------------------------
### Include image-q as Global Variable in Browser
Source: https://github.com/ibezkrovnyi/image-quantization/blob/main/README.md
This HTML snippet demonstrates how to include the `image-q` library directly in a web browser as a global variable using a `
```
--------------------------------
### Import image-q as ES6 Module
Source: https://github.com/ibezkrovnyi/image-quantization/blob/main/README.md
This snippet demonstrates how to import the `image-q` library using ES6 module syntax. It will import either the ESM (ESNext) or UMD version depending on the bundler or Node.js environment.
```javascript
import * as iq from 'image-q';
```
--------------------------------
### Writing Quantized Image Data to PNG
Source: https://github.com/ibezkrovnyi/image-quantization/blob/main/packages/image-q/API-README.md
Demonstrates how to convert the quantized `outPointContainer` to a `Uint8Array` and then write it to a PNG file using the `pngjs` library and Node.js `fs` module.
```ts
png.data = outPointContainer.toUint8Array();
fs.writeFileSync('filename.png', PNG.sync.write(png));
```
--------------------------------
### Generate Image Palette with RGBQuant
Source: https://github.com/ibezkrovnyi/image-quantization/blob/main/packages/image-q/API-README.md
This snippet demonstrates how to generate a color palette from an image using the `RGBQuant` quantizer. It initializes a `PointContainer` from an HTML image element, sets up a `Euclidean` distance calculator, and then samples the image to create a palette. Multiple images can be sampled to create a mutual palette.
```javascript
// desired colors number
var targetColors = 256;
// create pointContainer and fill it with image
var pointContainer = iq.utils.PointContainer.fromHTMLImageElement(img);
// create chosen distance calculator (see classes inherited from `iq.distance.AbstractDistanceCalculator`)
var distanceCalculator = new iq.distance.Euclidean();
// create chosen palette quantizer (see classes implementing `iq.palette.AbstractPaletteQuantizer`)
var paletteQuantizer = new iq.palette.RGBQuant(distanceCalculator, targetColors);
// feed out pointContainer filled with image to paletteQuantizer
paletteQuantizer.sample(pointContainer);
... (you may sample more than one image to create mutual palette)
// take generated palette
var palette = paletteQuantizer.quantizeSync();
```
--------------------------------
### PointContainer Image Import API
Source: https://github.com/ibezkrovnyi/image-quantization/blob/main/packages/image-q/API-README.md
Lists various methods available in the PointContainer class for importing image data from different sources like HTMLCanvasElement, ImageData, Uint8Array, HTMLImageElement, and Node.js Buffer.
```APIDOC
PointContainer:
fromHTMLCanvasElement:
Source: HTMLCanvasElement
fromImageData:
Source: ImageData (ctx.getImageData())
Source: Array
fromUint8Array:
Source: Uint8ClampedArray (ctx.getImageData().data)
Source: deprecated CanvasPixelArray (ctx.getImageData().data)
Source: Uint8Array
fromHTMLImageElement:
Source: HTMLImageElement
fromUint32Array:
Source: Uint32Array
fromBuffer:
Source: Buffer (Node.js)
```
--------------------------------
### Synchronous Image Quantization with ErrorDiffusionArray
Source: https://github.com/ibezkrovnyi/image-quantization/blob/main/packages/image-q/API-README.md
Shows how to apply an `ErrorDiffusionArray` image quantizer synchronously. It initializes the quantizer with a distance calculator and a specific kernel (Jarvis), then processes an input point container against a palette.
```ts
const imageQuantizer = new ErrorDiffusionArray(
distanceCalculator,
ErrorDiffusionArrayKernel.Jarvis,
);
const outPointContainer = imageQuantizer.quantizeSync(
inPointContainer,
palette,
);
```
--------------------------------
### Apply Color Palette to Image Data (Async and Sync)
Source: https://github.com/ibezkrovnyi/image-quantization/blob/main/packages/image-q/API-README.md
This API applies a given `Palette` to a `PointContainer`, returning a new `PointContainer` with the color-reduced image. It provides both asynchronous (Promise-based) and synchronous methods. Optional parameters include the color distance formula and the image quantization algorithm. The asynchronous version also supports a progress callback.
```ts
import { applyPalette } from 'image-q'; // or const applyPalette = require('image-q').applyPalette
const outPointContainer = await applyPalette(pointContainer, palette, {
colorDistanceFormula: 'euclidean', // optional
imageQuantization: 'floyd-steinberg', // optional
onProgress: (progress) => console.log('applyPalette', progress), // optional
});
```
```ts
import { applyPaletteSync } from 'image-q'; // or const applyPaletteSync = require('image-q').applyPaletteSync
const outPointContainer = applyPaletteSync(pointContainer, palette, {
colorDistanceFormula: 'euclidean', // optional
imageQuantization: 'floyd-steinberg', // optional
});
```
--------------------------------
### Convert 24-bit PNG to 8-bit Indexed Image with image-q
Source: https://github.com/ibezkrovnyi/image-quantization/blob/main/packages/image-q/API-README.md
This snippet demonstrates how to read a 24-bit PNG file, convert its pixel data into a `PointContainer`, build a color palette from it, and then apply that palette to the image to reduce its color depth to 8-bit indexed. It uses `pngjs` for file I/O and `image-q` for quantization.
```ts
import { PNG } from 'pngjs';
import { buildPaletteSync, utils } from 'image-q';
// read file
const { data, width, height } = PNG.sync.read(fs.readFileSync('file.png'));
const inPointContainer = utils.PointContainer.fromUint8Array(
data,
width,
height,
);
// convert
const palette = buildPaletteSync([inPointContainer]);
const outPointContainer = applyPaletteSync(inPointContainer, palette);
// use outPointContainer.toUint8Array() somehow
```
--------------------------------
### Palette Quantizers API Reference
Source: https://github.com/ibezkrovnyi/image-quantization/blob/main/packages/image-q/API-README.md
Lists available palette quantization algorithms, including NeuQuant, RGBQuant, WuQuant, and NeuQuantFloat, with notes on their calculation methods.
```APIDOC
API: NeuQuant
Description: original code ported, integer calculations
API: RGBQuant
Description:
API: WuQuant
Description:
API: NeuQuantFloat
Description: floating-point calculations
```
--------------------------------
### Apply Generated Palette to Image (Dithering)
Source: https://github.com/ibezkrovnyi/image-quantization/blob/main/packages/image-q/API-README.md
This snippet shows how to apply a previously generated color palette to an image using the `NearestColor` image quantizer, effectively performing image dithering. It takes the original `PointContainer` and the generated `palette` as input to produce a new `PointContainer` with the quantized image.
```javascript
// create image quantizer (see classes implementing `iq.image.AbstractImageQuantizer`)
var imageQuantizer = new iq.image.NearestColor(distanceCalculator);
// apply palette to image
var resultPointContainer = imageQuantizer.quantizeSync(pointContainer, palette);
```
--------------------------------
### image-q Breaking API Changes (v2.1.1 and v2.0.1-2.0.4)
Source: https://github.com/ibezkrovnyi/image-quantization/blob/main/README.md
This section details significant breaking changes introduced in `image-q` versions 2.1.1 and 2.0.1-2.0.4. It lists renamed methods and properties, as well as changes in color distance algorithm names and `PointContainer` static methods.
```APIDOC
Version 2.1.1:
PaletteQuantizer#quantize => PaletteQuantizer#quantizeSync
ImageQuantizer#quantize => ImageQuantizer#quantizeSync
Version 2.0.1 - 2.0.4 (2018-02-22):
EuclideanRgbQuantWOAlpha => EuclideanBT709NoAlpha
EuclideanRgbQuantWithAlpha => EuclideanBT709
ManhattanSRGB => ManhattanBT709
IImageDitherer => AbstractImageQuantizer
IPaletteQuantizer => AbstractPaletteQuantizer
PointContainer.fromNodeCanvas => PointContainer.fromHTMLCanvasElement
PointContainer.fromArray => PointContainer.fromUint8Array
PointContainer.fromBuffer (Node.js, new)
CMETRIC => CMetric
PNGQUANT => PNGQuant
SSIM Class => ssim function
```
--------------------------------
### Color Conversion API
Source: https://github.com/ibezkrovnyi/image-quantization/blob/main/packages/image-q/API-README.md
Provides a set of utility functions for converting colors between various standard color spaces, including CIE L*a*b*, CIE RGB, HSL, and CIE XYZ.
```APIDOC
lab2rgb: CIE L*a*b* => CIE RGB
lab2xyz: CIE L*a*b* => CIE XYZ
rgb2hsl: CIE RGB => HSL
rgb2lab: CIE RGB => CIE L*a*b*
rgb2xyz: CIE RGB => CIE XYZ
xyz2lab: CIE XYZ => CIE L*a*b*
xyz2rgb: CIE XYZ => CIE RGB
```
--------------------------------
### Output PointContainer API Reference
Source: https://github.com/ibezkrovnyi/image-quantization/blob/main/packages/image-q/API-README.md
Details methods available on `PointContainer` for converting image data to standard JavaScript typed arrays, specifically `toUint8Array` and `toUint32Array`.
```APIDOC
API: PointContainer.toUint8Array
Description: Returns Uint8Array
API: PointContainer.toUint32Array
Description: Returns Uint32Array
```
--------------------------------
### Color Distance Calculation APIs
Source: https://github.com/ibezkrovnyi/image-quantization/blob/main/packages/image-q/API-README.md
Provides a list of available color distance calculation algorithms, including Euclidean, Manhattan, CIEDE2000, CIE94, CMetric, PNGQuant, and specialized BT.709 versions.
```APIDOC
Color Distance Algorithms:
Euclidean:
Description: 1/1/1/1 coefficients
Originally used by: WuQuant
EuclideanBT709:
Description: BT.709 sRGB coefficients
Manhattan:
Description: 1/1/1/1 coefficients
Originally used by: NeuQuant
ManhattanBT709:
Description: BT.709 sRGB coefficients
CIEDE2000:
Description: CIEDE2000 (very slow)
CIE94Textiles:
Description: CIE94 implementation for textiles
CIE94GraphicArts:
Description: CIE94 implementation for graphic arts
CMetric:
Description: see http://www.compuphase.com/cmetric.htm
PNGQuant:
Description: used in PNGQuant tools
EuclideanBT709NoAlpha:
Description: BT.709 sRGB coefficients
Originally used by: RGBQuant
ManhattanNommyde:
Description: discussion https://github.com/igor-bezkrovny/image-quantization/issues/4#issuecomment-234527620
```
--------------------------------
### API Reference: ImageQuantization Type
Source: https://github.com/ibezkrovnyi/image-quantization/blob/main/packages/image-q/API-README.md
Defines the available string constants for `ImageQuantization`, specifying the algorithm used for applying the palette to the image (dithering or nearest color matching).
```APIDOC
export type ImageQuantization =
| 'nearest'
| 'riemersma'
| 'floyd-steinberg'
| 'false-floyd-steinberg'
| 'stucki'
| 'atkinson'
| 'jarvis'
| 'burkes'
| 'sierra'
| 'two-sierra'
| 'sierra-lite';
```
--------------------------------
### Importing HTML Canvas Element into PointContainer
Source: https://github.com/ibezkrovnyi/image-quantization/blob/main/packages/image-q/API-README.md
Demonstrates how to import an HTMLCanvasElement into a PointContainer object for image processing.
```typescript
const canvas = document.querySelector('#canvas');
const pointContainer = PointContainer.fromHTMLCanvasElement(canvas);
```
--------------------------------
### Apply Semi-Transparent Background with CSS Gradients
Source: https://github.com/ibezkrovnyi/image-quantization/blob/main/packages/demo/index.html
This CSS rule defines a semi-transparent checkerboard background using multiple linear gradients. It includes vendor prefixes for Mozilla (-moz-) and Webkit (-webkit-) browsers to ensure broad compatibility. The background size and position are adjusted to create the desired pattern.
```CSS
.image-semi-transparent-background { background-image: -moz-linear-gradient(45deg, #EEE 25%, transparent 25%), -moz-linear-gradient(-45deg, #EEE 25%, transparent 25%), -moz-linear-gradient(45deg, transparent 75%, #EEE 75%), -moz-linear-gradient(-45deg, transparent 75%, #EEE 75%); background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(.25, #EEE), color-stop(.25, transparent)), -webkit-gradient(linear, 0 0, 100% 100%, color-stop(.25, #EEE), color-stop(.25, transparent)), -webkit-gradient(linear, 0 100%, 100% 0, color-stop(.75, transparent), color-stop(.75, #EEE)), -webkit-gradient(linear, 0 0, 100% 100%, color-stop(.75, transparent), color-stop(.75, #EEE)); -moz-background-size:20px 20px; background-size:20px 20px; -webkit-background-size:20px 21px; /* override value for shitty webkit */ background-position:0 0, 10px 0, 10px -10px, 0px 10px; }
```
--------------------------------
### API Reference: PaletteQuantization Type
Source: https://github.com/ibezkrovnyi/image-quantization/blob/main/packages/image-q/API-README.md
Defines the available string constants for `PaletteQuantization`, specifying the algorithm used for generating the color palette during the quantization process.
```APIDOC
export type PaletteQuantization =
| 'neuquant'
| 'neuquant-float'
| 'rgbquant'
| 'wuquant';
```
--------------------------------
### Convert Quantized Image to Uint8Array
Source: https://github.com/ibezkrovnyi/image-quantization/blob/main/packages/image-q/API-README.md
After applying a palette and obtaining a `resultPointContainer`, this snippet demonstrates how to convert the quantized image data into a `Uint8Array` for further processing, display, or saving.
```javascript
var uint8array = resultPointContainer.toUint8Array();
```
--------------------------------
### Image Quantizers API Reference
Source: https://github.com/ibezkrovnyi/image-quantization/blob/main/packages/image-q/API-README.md
Provides a list of available image quantization algorithms, including NearestColor and various Error Diffusion methods like FloydSteinberg, Atkinson, and Jarvis, noting supported propagation modes.
```APIDOC
API: NearestColor
Description:
API: ErrorDiffusionArray
Description: 2 modes of error propagation are supported: `xnview` and `gimp`
Sub-APIs:
FloydSteinberg
FalseFloydSteinberg
Stucki
Atkinson
Jarvis
Burkes
Sierra
TwoSierra
SierraLite
API: ErrorDiffusionRiemersma
Description: Hilbert space-filling curve is used
```
--------------------------------
### API Reference: ColorDistanceFormula Type
Source: https://github.com/ibezkrovnyi/image-quantization/blob/main/packages/image-q/API-README.md
Defines the available string constants for `ColorDistanceFormula`, used to specify the color distance calculation method in image quantization operations. These formulas determine how the 'distance' between two colors is measured.
```APIDOC
export type ColorDistanceFormula =
| 'cie94-textiles'
| 'cie94-graphic-arts'
| 'ciede2000'
| 'color-metric'
| 'euclidean'
| 'euclidean-bt709-noalpha'
| 'euclidean-bt709'
| 'manhattan'
| 'manhattan-bt709'
| 'manhattan-nommyde'
| 'pngquant';
```
--------------------------------
### Structural Similarity (SSIM) Calculation
Source: https://github.com/ibezkrovnyi/image-quantization/blob/main/packages/image-q/API-README.md
Calculates the Structural Similarity Index (SSIM) between two `PointContainer` objects. SSIM is a perceptual metric that quantifies the similarity between two images, often used for image quality assessment.
```APIDOC
ssim(pointContainer1: PointContainer, pointContainer2: PointContainer): number
```
```typescript
const similarity = ssim(pointContainer1, pointContainer2);
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.