代码之家  ›  专栏  ›  技术社区  ›  Lorenzo D'Arsiè

将PIL图像转换为wxPython位图图像

  •  2
  • Lorenzo D'Arsiè  · 技术社区  · 8 年前

    在网上,我能找到的最好的建议是

    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
    

    1 回复  |  直到 8 年前
        1
  •  4
  •   Dalen    8 年前

    互联网上到处都有关于如何做到这一点的例子。但也有一些条件没有涵盖在内。 尤其是在将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")
    
    
    推荐文章