PIL:将字节数组转换为图像
我正在尝试通过Image.open
和Image.verify()
不通过将字节数组写入磁盘来验证字节数组,然后使用来打开它im =
Image.open()
。我看了.readfrombuffer()
and.readfromstring()
方法,但是我需要图像的大小(只有将字节流转换为图像时才能得到)。
我的读取功能如下所示:
def readimage(path):
bytes = bytearray()
count = os.stat(path).st_size / 2
with open(path, "rb") as f:
print "file opened"
bytes = array('h')
bytes.fromfile(f, count)
return bytes
然后作为基本测试,我尝试将字节数组转换为图像:
bytes = readimage(path+extension)
im = Image.open(StringIO(bytes))
im.save(savepath)
如果有人知道我在做什么错,或者有一种更优雅的方法将这些字节转换为对我有真正帮助的图像。
PS:我以为我需要字节数组,因为我对字节进行了处理(使它们出现图像错误)。这确实可行,但我想做到这一点而不将其写入磁盘,然后再次从磁盘打开映像文件以检查其是否损坏。
编辑:它给我的只是一个 IOError: cannot identify image file
-
如果您使用
bytearrays
,则必须使用io.BytesIO
。您也可以直接将文件读取到bytearray
。import os import io import PIL.Image as Image from array import array def readimage(path): count = os.stat(path).st_size / 2 with open(path, "rb") as f: return bytearray(f.read()) bytes = readimage(path+extension) image = Image.open(io.BytesIO(bytes)) image.save(savepath)