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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18491416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:52:48  来源:igfitidea点击:

PIL: Convert Bytearray to Image

pythonarraysimagebytepython-imaging-library

提问by ato

I am trying to verify a bytearray with Image.openand 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).

我正在尝试先将字节数组写入磁盘Image.openImage.verify()不将其写入磁盘,然后使用im = Image.open(). 我查看了.readfrombuffer()and.readfromstring()方法,但在那里我需要图像的大小(只有在将字节流转换为图像时才能获得)。

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:

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

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.

PS:我认为我需要字节数组,因为我对字节进行了操作(对图像进行故障处理)。这确实有效,但我不想将其写入磁盘,然后再次从磁盘打开图像文件以检查它是否损坏。

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

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

采纳答案by Viktor Kerkez

If you manipulate with bytearrays, then you have to use io.BytesIO. Also you can read a file directly to a bytearray.

如果您使用 进行操作bytearrays,那么您必须使用io.BytesIO. 您也可以将文件直接读取到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)