【发布时间】:2015-07-01 10:56:19
【问题描述】:
我正在使用来自this post 的以下代码(几乎没有修改)。该脚本只需要一个十六进制颜色数组并从中写入一个 PNG 图像。我正在尝试使其适应 Py3,但出了点问题。
import zlib, struct
def png_pack(png_tag, data):
chunk_head = png_tag + data
return (struct.pack("!I", len(data)) +
chunk_head +
struct.pack("!I", 0xFFFFFFFF & zlib.crc32(chunk_head)))
def write_png(buf, width, height):
# reverse the vertical line order and add null bytes at the start
width_byte_4 = width * 4
raw_data = b''.join(b'\x00' + buf[span:span + width_byte_4]
for span in range((height - 1) * width * 4, -1, - width_byte_4))
return b''.join([
b'\x89PNG\r\n\x1a\n',
png_pack(b'IHDR', struct.pack("!2I5B", width, height, 8, 6, 0, 0, 0)),
png_pack(b'IDAT', zlib.compress(raw_data, 9)),
png_pack(b'IEND', b'')])
def saveAsPNG(array, filename):
import struct
if any([len(row) != len(array[0]) for row in array]):
raise ValueError("Array should have elements of equal size")
#First row becomes top row of image.
flat = []
map(flat.extend, reversed(array))
#Big-endian, unsigned 32-byte integer.
buf = b''.join([struct.pack('>I', ((0xffFFff & i32)<<8)|(i32>>24) )
for i32 in flat]) #Rotate from ARGB to RGBA.
#print(type(buf))
data = write_png(buf, len(array[0]), len(array))
f = open(filename, 'wb')
f.write(data)
f.close()
saveAsPNG([[0xffFF0000, 0xffFFFF00],
[0xff00aa77, 0xff333333]], 'test.png')
它与 Python 2.7 完美配合,在 Python 3 上运行时不会出现任何错误。但是生成的图像是空的……我不知道问题出在哪里。我试图用starmap 替换map,但没有任何改变。我检查了buf 是bytes 而不是string,它是。我真的不知道为什么它不能正确写入文件。
有什么线索吗?
【问题讨论】:
标签: arrays python-3.x png