image-in-browser
Version:
Package for encoding / decoding images, transforming images, applying filters, drawing primitives on images on the client side (no need for server Node.js)
96 lines • 3.03 kB
JavaScript
import { ColorUint8 } from '../../color/color-uint8.js';
import { PaletteUint8 } from '../../image/palette-uint8.js';
export class GifColorMap {
get numColors() {
return this._numColors;
}
get palette() {
return this._palette;
}
get bitsPerPixel() {
return this._bitsPerPixel;
}
set transparent(v) {
this._transparent = v;
}
get transparent() {
return this._transparent;
}
constructor(numColors, palette) {
this._numColors = numColors;
this._palette = palette !== null && palette !== void 0 ? palette : new PaletteUint8(numColors, 3);
this._bitsPerPixel = GifColorMap.bitSize(numColors);
}
static bitSize(n) {
for (let i = 1; i <= 8; i++) {
if (1 << i >= n) {
return i;
}
}
return 0;
}
static from(other) {
const palette = PaletteUint8.from(other._palette);
const r = new GifColorMap(other.numColors, palette);
r._bitsPerPixel = other._bitsPerPixel;
r._transparent = other._transparent;
return r;
}
getColor(index) {
const r = this.getRed(index);
const g = this.getGreen(index);
const b = this.getBlue(index);
const a = this.getAlpha(index);
return ColorUint8.rgba(r, g, b, a);
}
setColor(index, r, g, b) {
this._palette.setRgb(index, r, g, b);
}
findColor(r, g, b, a) {
let closestDistance = -1;
let closestIndex = -1;
for (let i = 0; i < this._numColors; ++i) {
const pr = this._palette.getRed(i);
const pg = this._palette.getGreen(i);
const pb = this._palette.getBlue(i);
const pa = this._palette.getAlpha(i);
if (pr === r && pg === g && pb === b && pa === a) {
return i;
}
const dr = r - pr;
const dg = g - pg;
const db = b - pb;
const da = a - pa;
const d2 = dr * dr + dg * dg + db * db + da * da;
if (closestIndex === -1 || d2 < closestDistance) {
closestIndex = i;
closestDistance = d2;
}
}
return closestIndex;
}
getRed(color) {
return Math.trunc(this._palette.getRed(color));
}
getGreen(color) {
return Math.trunc(this._palette.getGreen(color));
}
getBlue(color) {
return Math.trunc(this._palette.getBlue(color));
}
getAlpha(color) {
return color === this._transparent ? 0 : 255;
}
getPalette() {
if (this._transparent === undefined) {
return this._palette;
}
const p = new PaletteUint8(this._palette.numColors, 4);
const l = this._palette.numColors;
for (let i = 0; i < l; ++i) {
p.setRgba(i, this.getRed(i), this.getGreen(i), this.getBlue(i), this.getAlpha(i));
}
return p;
}
}
//# sourceMappingURL=gif-color-map.js.map