2013-08-28 108 views
9

我試圖驗證與Image.openImage.verify()的字節陣列,而不先將其寫入磁盤,然後用im = Image.open()將其打開。我查看了.readfrombuffer().readfromstring()方法,但是我需要圖像的大小(我只能在將字節流轉換爲圖像時獲得)。PIL:將Bytearray轉換爲圖像

我讀功能如下:

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

+0

爲什麼不將圖像讀入numpy數組? –

+1

@ViktorKerkez,因爲我想操縱圖像的字節。我有處理代碼的操作部分,但現在我想驗證輸出圖像實際上並沒有完全破碎。所以我_have_與bytearrays – ato

回答

10

如果用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) 
+0

工作你爲什麼一半st_size?爲什麼要聲明'count'呢? – jdborg

+1

@jdborg因爲OP在他的問題中做了同樣的事情。 :)我只是複製/粘貼代碼並修復錯誤。 –

+0

另外值得指出的是'bytes'是Python中的一個保留字 –