我正在尝试使用 Image.open
和 Image.verify()
验证字节数组,而不是先将其写入磁盘,然后使用 im = 打开它图片.open()
。我查看了 .readfrombuffer()
和 .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)
如果有人知道我做错了什么,或者是否有更优雅的方法将这些字节转换为图像,那将真正帮助我。
P.S.:我认为我需要 bytearray,因为我对字节进行操作(对图像进行故障处理)。这确实有效,但我想在不将其写入磁盘的情况下执行此操作,然后再次从磁盘打开图像文件以检查它是否已损坏。
编辑:它给我的只是一个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)
关于python - PIL : Convert Bytearray to Image,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18491416/