PIL: Convert Bytearray to Image

匿名 (未验证) 提交于 2019-12-03 01:57:01

问题:

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.: 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.

Edit: All it gives me is a IOError: cannot identify image file

回答1:

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) 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!