PIL:将字节数组转换为图像

发布于 2021-01-29 19:34:30

我正在尝试通过Image.openImage.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

关注者
0
被浏览
179
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    如果您使用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)
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看