import { PNG } from 'pngjs' ; import RGBAColor from '../types/RGBAColor' ; param { PNG } png returns { Promise < string > } function blobToBase64 ( png ) { const chunks = [ ] ; return new Promise ( ( resolve ) => { png . pack ( ) ; png . on ( 'data' , ( c ) => chunks . push ( c ) ) ; png . on ( 'end' , ( ) => { const result = Buffer . concat ( chunks ) ; resolve ( 'data:image/png;base64,' + result . toString ( 'base64' ) ) ; } ) ; } ) ; } param { PNG } png returns { string } function getBuffer ( png ) { return PNG . sync . write ( png ) ; } param { string } hex returns { RGBAColor } function getRgbaColor ( hex = '000000FF' ) { const colors = [ ... hex . match ( /^([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i ) ?? [ ] ] ; const alpha = parseInt ( colors [ 4 ] , 16 ) ; if ( colors . length >= 3 ) { return { red : parseInt ( colors [ 1 ] , 16 ) , green : parseInt ( colors [ 2 ] , 16 ) , blue : parseInt ( colors [ 3 ] , 16 ) , alpha : ! isNaN ( alpha ) ? alpha : 255 } ; } return { red : 0 , green : 0 , blue : 0 , alpha : 255 } ; } param { RGBAColor } a param { RGBAColor } b returns { boolean } function isEqualColor ( a , b ) { return a . red === b . red && a . green === b . green && a . blue === b . blue ; } param { number [ ] } bitmap param { number } width param { number } height returns { PNG } function render ( bitmap , width , height , backgroundColor ? , foregroundColor ? ) { const png = new PNG ( { width , height } ) ; const backgroundColorRgba = getRgbaColor ( backgroundColor ) ; const foregroundColorRgba = getRgbaColor ( foregroundColor ) ; let i = 0 ; for ( let y = 0 ; y < height ; y ++ ) { for ( let x = 0 ; x < width ; x ++ ) { const color = { red : bitmap [ i ] , green : bitmap [ i + 1 ] , blue : bitmap [ i + 2 ] } ; const rgba = isEqualColor ( color , backgroundColorRgba ) ? backgroundColorRgba : foregroundColorRgba ; const pos = ( png . width * y + x ) << 2 ; png . data [ pos ] = rgba . red ; png . data [ pos + 1 ] = rgba . green ; png . data [ pos + 2 ] = rgba . blue ; png . data [ pos + 3 ] = rgba . alpha || 0 ; i += 3 ; } } return png ; } export default { blobToBase64 , getBuffer , getRgbaColor , render } ;