import IImageData from '../model/IImageData' ; import Palette from '../model/Palette' ; import Pixels from '../model/Pixels' ; import { ColorSpace } from '../profiles/ColorSpaces' ; /**
 * Maps a color to a palette.
 */ export default class Quantizer { private colorspace : ColorSpace ; private palette : Palette ; constructor ( palette , colorspace ) { this . colorspace = colorspace ; this . palette = new Palette ( palette . colors . map ( p => colorspace ( p ) ) ) ; this . palette . enabled = palette . enabled ; } public distance = ( realPixel , paletteIndex ) : number => { const realPixelConverted = this . colorspace ( realPixel ) ; const palettePixel = this . palette . colors [ paletteIndex ] ; return Math . sqrt ( ( realPixelConverted [ 0 ] - palettePixel [ 0 ] ) ** 2 + ( realPixelConverted [ 1 ] - palettePixel [ 1 ] ) ** 2 + ( realPixelConverted [ 2 ] - palettePixel [ 2 ] ) ** 2 ) ; } ; param pixel returns public quantizePixel ( pixel ) { return this . palette . enabled . map ( index => [ index , this . distance ( pixel , index ) ] ) . reduce ( ( acc , current ) => ( current [ 1 ] < acc [ 1 ] ? current : acc ) , [ null , Number . POSITIVE_INFINITY ] ) [ 0 ] ; } public quantizeImage ( image ) { const result = [ ] ; for ( let y = 0 ; y < image . height ; y ++ ) { for ( let x = 0 ; x < image . width ; x ++ ) { result . push ( this . quantizePixel ( Pixels . peek ( image , x , y ) ) ) ; } } return result ; } }