photopea / UPNG.js

Fast and advanced PNG (APNG) decoder and encoder (lossy / lossless)
MIT License
2.1k stars 259 forks source link

data array of wrong size #9

Closed jonathanlurie closed 7 years ago

jonathanlurie commented 7 years ago

Hi, When I decode a png, the object given by UPNG has a wrong sized data array. I made a test image here (it is VERY small):
damier2_alpha and here is the screen capture from Chome's console: upng2

The image is 12 pixels wide, 7 pixels high and has 4 components. This should give a data array of size 336 but instead gives a larger array (size 343).

I made other tests with other images and every time, the final array size is : w*h*nc + h instead of just w*h*nc , where nc is the number of components per pixel.
I checked with other images and the issue is always here. The last h numbers of the array seem to be fake data, only 0, 1, 255, and 254.

In case someone is interested, here is the workaround I use:

var pngData = png.decode( inputBuffer );
var ncpp = Math.round(pngData.data.length / (pngData.width*pngData.height) );
var croppedArray = new pngData.data.constructor( pngData.data.buffer, 0, pngData.width * pngData.height * ncpp);

Cheers.

Update: the method UPNG.decode._inflate just calls pako.inflate, and Pako seems to be responsible for the wrong size...

photopea commented 7 years ago

Hi Jonathan, I never noticed it. I think, that Deflate algorithm can compress data into sub-byte size (the size of a compressed image (in bits) is not a multiple of 8). But PNG requires storing whole bytes. PNG encoders probably fill remaining bits with zeros, and after the decompression these zeros generate extra data.

Anyway, if you want to be able to read any PNG file into a RGBA, 8 bits per channel format, without caring too much about details, I recommend using the UPNG.toRGBA8(img) afterwards. That should return a correct data of a correct size.

photopea commented 7 years ago

So I think I can close it now.

jonathanlurie commented 7 years ago

Ah ok, I'll try with UPNG.toRGBA8(img) then! Thanks