Loop cleanup, python 3 compatibility

This commit is contained in:
wiredfool 2016-12-30 23:10:47 +00:00
parent 3d185ee857
commit 31c204eae4

View File

@ -28,6 +28,7 @@ import os
__version__ = "0.3" __version__ = "0.3"
i8 = _binary.i8 i8 = _binary.i8
o8 = _binary.o8
i16 = _binary.i16be i16 = _binary.i16be
@ -110,41 +111,37 @@ def _save(im, fp, filename):
pinmin = 0 pinmin = 0
# Maximum Byte value (255 = 8bits per pixel) # Maximum Byte value (255 = 8bits per pixel)
pinmax = 255 pinmax = 255
# Image name (79 characters max) # Image name (79 characters max, truncated below in write)
imgName = os.path.splitext(os.path.basename(filename))[0][0:78] imgName = os.path.splitext(os.path.basename(filename))[0]
if str is not bytes:
imgName = imgName.encode('ascii', 'ignore')
# Standard representation of pixel in the file # Standard representation of pixel in the file
colormap = 0 colormap = 0
channels = []
for channelIndex in range(0, z):
channelData = list(im.getdata(channelIndex))
channels.append(channelData)
fp.write(struct.pack('>h', magicNumber)) fp.write(struct.pack('>h', magicNumber))
fp.write(struct.pack('c', chr(rle))) fp.write(o8(rle))
fp.write(struct.pack('c', chr(bpc))) fp.write(o8(bpc))
fp.write(struct.pack('>H', dim)) fp.write(struct.pack('>H', dim))
fp.write(struct.pack('>H', x)) fp.write(struct.pack('>H', x))
fp.write(struct.pack('>H', y)) fp.write(struct.pack('>H', y))
fp.write(struct.pack('>H', z)) fp.write(struct.pack('>H', z))
fp.write(struct.pack('>l', pinmin)) fp.write(struct.pack('>l', pinmin))
fp.write(struct.pack('>l', pinmax)) fp.write(struct.pack('>l', pinmax))
for i in range(0, 4):
fp.write(struct.pack('c', chr(0))) fp.write(struct.pack('4s', b'')) # dummy
for c in imgName: fp.write(struct.pack('79s', imgName)) # truncates to 79 chars
fp.write(struct.pack('c', c)) fp.write(struct.pack('s', b'')) # force null byte after imgname
fp.write(struct.pack('c', chr(0)))
if len(imgName) < 78:
charIndex = len(imgName)
for charIndex in range(len(imgName), 79):
fp.write(struct.pack('c', chr(0)))
fp.write(struct.pack('>l', colormap)) fp.write(struct.pack('>l', colormap))
for i in range(0, 404):
fp.write(struct.pack('c', chr(0))) fp.write(struct.pack('404s', b'')) # dummy
for zChannel in range(0, z):
dIndex = 0 #assert we've got the right number of bands.
for yPos in range(0, y): if len(im.getbands()) != z:
for xPos in range(0, x): raise ValueError("incorrect number of bands in SGI write: %s vs %s" %
fp.write(struct.pack('c', chr(channels[zChannel][dIndex]))) (z, len(im.getbands())))
dIndex += 1
for channel in im.split():
fp.write(channel.tobytes())
fp.close() fp.close()