PIL:将Bytearray转换为Image [英] PIL: Convert Bytearray to Image
问题描述
我正在尝试使用 Image.open
和 Image.verify()
验证一个bytearray,而不将其写入首先是磁盘然后用 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
然后作为基本测试,我尝试将bytearray转换为图像:
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.
PS:我认为我需要bytearray,因为我对字节进行了操作(故障)他们的图像)。这确实有效,但是我想这样做而不将其写入磁盘,然后再次从磁盘打开图像文件以检查它是否坏了。
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:无法识别图像文件
All it gives me is a IOError: cannot identify image file
推荐答案
如果使用 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 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:将Bytearray转换为Image的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!