2017-10-06 112 views
1

我可以加載JPEG圖像,將其轉換爲位圖並將其繪製在wx應用程序中。然而,我很難將PIL圖像對象轉換爲可以繪製到wx應用程序中的位圖。將PIL圖像轉換爲wxPython位圖圖像

在線,我能找到的最好的建議是做一些像

wx.Bitmap(PIL_image.tobytes()) 

然而,這給了我下面的錯誤

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 59: invalid start byte 

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc8 in position 51: invalid continuation byte 

有某人有關如何解決這一問題的好建議?謝謝!

回答

2

有關如何做到這一點的互聯網上的例子。但是有些條件沒有包含在其中。 特別是在將wxBitmap()轉換回PIL Image()時。

我在這裏發佈我的這些函數的修改版本。轉換速度快且可靠。



from PIL import Image 
import wx 

def PIL2wx (image): 
    width, height = image.size 
    return wx.BitmapFromBuffer(width, height, image.tobytes()) 

def wx2PIL (bitmap): 
    size = tuple(bitmap.GetSize()) 
    try: 
     buf = size[0]*size[1]*3*"\x00" 
     bitmap.CopyToBuffer(buf) 
    except: 
     del buf 
     buf = bitmap.ConvertToImage().GetData() 
    return Image.frombuffer("RGB", size, buf, "raw", "RGB", 0, 1) 


# Suggested usage is to put the code in a separate file called 
# helpers.py and use it as this: 

from helpers import wx2PIL, PIL2wx 
from PIL import Image 

i = Image.open("someimage.jpg").convert("RGB") 
wxb = PIL2wx(i) 
# Now draw wxb to screen and let user draw something over it using wxDC() and so on... 
# Then pick a wx.Bitmap() from wx.DC() and do something like: 
wx2PIL(thedc.GetAsBitmap()).save("some new image.jpg") 

+0

它的工作原理,謝謝,但我不得不修改它是這樣的:'返回wx.Bitmap.FromBuffer(寬度,高度,image.convert( 「RGB」)tobytes())' –

+0

確定你必須在位圖和FromBuffer之間添加一個額外的點?只是爲了確認它。因爲如果你這樣做了,那麼在我還不知道的新版本的wxPython中引入了一些更改。至於convert(),那麼,對不起,我忘了返回它。我刪除了它,因爲我的當前應用程序默認使用RGB,所以不需要額外的convert()。如果它存在,它只會使該功能廣泛使用,但在其他情況下會減慢它的功能。我使用PIL從相機準備圖像,然後在wx.Panel()上繪製它。所以每一個usec是寶貴的。 – Dalen

+0

是的,有變化。如果沒有這個點,你現在只會得到一個警告。我明白,關於RGB轉換。我剛剛評論過它,因爲它可能對其他人閱讀您的答案有用。 –