【问题标题】:PIL: Convert Bytearray to ImagePIL:将字节数组转换为图像
【发布时间】:2013-08-31 17:37:09
【问题描述】:

我正在尝试使用Image.openImage.verify() 验证字节数组,而无需先将其写入磁盘,然后再使用im = Image.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.:我认为我需要字节数组,因为我对字节进行操作(将它们的图像弄错)。这确实有效,但我想这样做而不是将其写入磁盘,然后再次从磁盘打开图像文件以检查它是否损坏。

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

【问题讨论】:

  • 为什么不将图像读入numpy数组?
  • @ViktorKerkez 因为我想操纵图像的字节。我有操作部分的工作代码,但现在我想验证输出图像实际上没有完全损坏。所以我必须使用字节数组

标签: python arrays image byte python-imaging-library


【解决方案1】:

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

【讨论】:

  • 为什么你只有一半的st_size?为什么要声明count
  • @jdborg 因为 OP 在他的问题中做了同样的事情。 :) 我只是复制/粘贴代码并修复了错误。
  • 另外值得指出的是bytes是Python中的保留字
猜你喜欢
  • 2016-01-11
  • 2017-06-25
  • 1970-01-01
  • 2015-08-16
  • 2013-05-19
  • 2010-09-27
  • 2013-01-14
相关资源
最近更新 更多