PIL:将字节数组转换为图像 [英] PIL: Convert Bytearray to Image
问题描述
我正在尝试使用 Image.open
和 Image.verify()
验证字节数组,而不先将其写入磁盘,然后使用 im = 打开它Image.open()
.我查看了 .readfrombuffer()
和 .readfromstring()
方法,但在那里我需要图像的大小(只有在将字节流转换为图片).
I am trying to verify a bytearray with Image.open
and Image.verify()
without writing it to disk first and then open it with im = Image.open()
. I looked at the .readfrombuffer()
and .readfromstring()
method, but there I need the size of the image (which I could only get when converting the bytestream to an image).
我的读取函数如下所示:
My Read-Function looks like this:
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
然后作为基本测试,我尝试将字节数组转换为图像:
Then as a basic test I try to convert the bytearray to an image:
bytes = readimage(path+extension)
im = Image.open(StringIO(bytes))
im.save(savepath)
如果有人知道我做错了什么,或者是否有更优雅的方法将这些字节转换为真正对我有帮助的图像.
If someone knows what I am doing wrong or if there is a more elegant way to convert those bytes into an image that'd really help me.
P.S.:我认为我需要字节数组,因为我对字节进行了操作(对图像进行故障处理).这确实有效,但我不想将其写入磁盘,然后再次从磁盘打开图像文件以检查它是否损坏.
P.S.: I thought I need the bytearray because I do manipulations on the bytes (glitch them images). This did work, but I wanted to do it without writing it to disk and then opening the imagefile from the disk again to check if it is broken or not.
它给我的只是一个IOError:无法识别图像文件
推荐答案
如果你用 bytearrays
操作,那么你必须使用 io.BytesIO
.您也可以将文件直接读取到 bytearray
.
If you manipulate with bytearrays
, then you have to use io.BytesIO
. Also you can read a file directly to a 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)
这篇关于PIL:将字节数组转换为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!