[英]PIL: Convert Bytearray to Image
我正在嘗試使用Image.open
和Image.verify()
驗證Image.open
, Image.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
然后作為基本測試,我嘗試將 bytearray 轉換為圖像:
bytes = readimage(path+extension)
im = Image.open(StringIO(bytes))
im.save(savepath)
如果有人知道我做錯了什么,或者是否有更優雅的方法將這些字節轉換為真正對我有幫助的圖像。
PS:我認為我需要字節數組,因為我對字節進行了操作(對圖像進行故障處理)。 這確實有效,但我不想將其寫入磁盤,然后再次從磁盤打開圖像文件以檢查它是否損壞。
編輯:它給我的只是一個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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.