有關如何做到這一點的互聯網上的例子。但是有些條件沒有包含在其中。 特別是在將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")
它的工作原理,謝謝,但我不得不修改它是這樣的:'返回wx.Bitmap.FromBuffer(寬度,高度,image.convert( 「RGB」)tobytes())' –
確定你必須在位圖和FromBuffer之間添加一個額外的點?只是爲了確認它。因爲如果你這樣做了,那麼在我還不知道的新版本的wxPython中引入了一些更改。至於convert(),那麼,對不起,我忘了返回它。我刪除了它,因爲我的當前應用程序默認使用RGB,所以不需要額外的convert()。如果它存在,它只會使該功能廣泛使用,但在其他情況下會減慢它的功能。我使用PIL從相機準備圖像,然後在wx.Panel()上繪製它。所以每一個usec是寶貴的。 – Dalen
是的,有變化。如果沒有這個點,你現在只會得到一個警告。我明白,關於RGB轉換。我剛剛評論過它,因爲它可能對其他人閱讀您的答案有用。 –