Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I round-trip an image using PyPNG?

Tags:

python

pypng

This seems fairly simple:

import png
rdr = png.Reader(filename='help.png')
width, height, pixels, metadata = rdr.read()
with open('help-new.png', 'w') as outfile:
    png.Writer(**metadata).write(outfile, pixels)

However, I can't open my new image because the file "appears to be damaged, corrupted, or too large". If I try to load the result back into PyPNG, I get this:

FormatError: FormatError: PNG file has invalid signature.

Additional info: The metadata looks like this:

'bitdepth': 8, 'interlace': 0, 'planes': 1,
'greyscale': False, 'alpha': False, 'size': (18, 18)

The first palette entry is (0, 0, 0, 0), while the others are all of the form (255, 255, 255, A) where A is between 0 and 255. The source file is 718 bytes, result file is 748 bytes.

like image 741
samwyse Avatar asked Dec 22 '25 04:12

samwyse


1 Answers

Open the output file in binary mode:

open('help-new.png', 'wb') as outfile:
                       ^
                       |
                  that's it,
                  right there

Otherwise the I/O layer might do newline translation which you never want for binary files.

like image 200
unwind Avatar answered Dec 23 '25 17:12

unwind