ato*_*ato 17 python arrays byte image python-imaging-library
我想验证一个字节组有Image.open
和Image.verify()
没有首先将其写入到磁盘,然后打开它im = Image.open()
.我查看了.readfrombuffer()
和.readfromstring()
方法,但是我需要图像的大小(我只能在将字节流转换为图像时才能获得).
我的Read-Function看起来像这样:
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
Run Code Online (Sandbox Code Playgroud)
然后作为基本测试,我尝试将bytearray转换为图像:
bytes = readimage(path+extension)
im = Image.open(StringIO(bytes))
im.save(savepath)
Run Code Online (Sandbox Code Playgroud)
如果有人知道我做错了什么,或者是否有更优雅的方式将这些字节转换为真正帮助我的图像.
PS:我认为我需要bytearray,因为我对字节进行了操作(故障图像).这确实有效,但我想这样做而不将其写入磁盘,然后再次从磁盘打开图像文件以检查它是否损坏.
编辑:它给我的全部是 IOError: cannot identify image file
Vik*_*kez 28
如果你操纵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)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
42637 次 |
最近记录: |