python - PIL : Convert Bytearray to Image

标签 python arrays image byte python-imaging-library

我正在尝试使用 Image.openImage.verify() 验证字节数组,而不是先将其写入磁盘,然后使用 im = 打开它图片.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

然后作为基本测试,我尝试将字节数组转换为图像:

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

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

P.S.:我认为我需要 bytearray,因为我对字节进行操作(对图像进行故障处理)。这确实有效,但我想在不将其写入磁盘的情况下执行此操作,然后再次从磁盘打开图像文件以检查它是否已损坏。

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

最佳答案

如果您使用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)

关于python - PIL : Convert Bytearray to Image,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18491416/

相关文章:

java - 加载图像作为资源返回 null

class - 如果我有实例列表,调用类函数的 Pythonic 方式

python - 如何在 Windows 7 64 位上安装 PyOpenSSL?

python - 无法在 Linux 上安装 Python 包

javascript - 为什么我不能更改已定义元素的 className

java - HTTP "Partial"Java 获取请求报文

python - 如何在样式表中使用非标准自定义字体?

algorithm - 需要帮助迭代数组,检索两种可能性,不重复,用于 Poker AI

在unix c中逐字节比较两张图片

php - 从php中的ttf-font获取单个字符的宽度?