drj11 / pypng

Pure Python library for PNG image encoding/decoding

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Bug in write_pnm()

opened this issue · comments

write_pnm() will fail in Python 3.x because it mixes string and binary writes to the same file. Writing strings to a file open in binary mode requires encoding that string, and vice versa.
I'm presuming you expect the output file to be in binary mode, so this is easily fixed by encoding the strings as they're written.

3599:
file.write('%s %d %d %d\n' % (fmt, width, height, maxval))
to
3599:
h = '%s %d %d %d\n' % (fmt, width, height, maxval)

3607:
file.write('P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\n'
'TUPLTYPE %s\nENDHDR\n' %
(width, height, planes, maxval, tupltype))
to
3607:
h = 'P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\nTUPLTYPE %s\nENDHDR\n' % (width, height, planes, maxval, tupltype)

Then insert this to write it to the file.
3610:
file.write(h.encode('ascii'))

Agreed, and your approach looks very reasonable.

Fixed pending a new release.