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

56

我正在尝试使用Image.openImage.verify()验证一个bytearray,而不是先将其写入磁盘,然后再用im = Image.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

然后作为一个基本测试,我尝试将bytearray转换为图像:

bytes = readimage(path+extension)
im = Image.open(StringIO(bytes))
im.save(savepath)

如果有人知道我做错了什么或者有更优雅的方法将这些字节转换为图像,那真的会很有帮助。

P.S.:我认为我需要bytearray是因为我对字节进行操作(扭曲它们的图像)。这确实起作用了,但我想在不将其写入磁盘并从磁盘再次打开图像文件来检查它是否损坏的情况下完成它。

编辑:它只给我一个IOError: cannot identify image file


为什么不将图像读入numpy数组? - Viktor Kerkez
1
因为我想要操作图像的字节。我已经有了操纵部分的工作代码,但是现在我想验证输出图像实际上并不完全损坏。所以我不得不使用字节数组。 - ato
1个回答

73

如果你要操作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)

为什么要将st_size减半?而且为什么要声明“count”? - joedborg
5
因为提问者在他的问题中也做了同样的事情。 :) 我只是复制粘贴了代码并修正了错误。 - Viktor Kerkez
19
值得一提的是,bytes 是 Python 中的一个保留字。 - Mike Young

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接