保存wxPython设备上下文绘制的图像

5 投票
2 回答
3552 浏览
提问于 2025-04-15 18:52

我需要能够保存设备上下文画布的状态为一张图片(格式无所谓)。我试过使用 dc.GetAsBitmap,但是它返回的位图不正确。我该怎么做呢?

2 个回答

1

你可以从这个链接中找到一些关于如何在wxPython中处理图像的内容。

6

我觉得这样做就可以了:

def saveSnapshot(dcSource):
    # based largely on code posted to wxpython-users by Andrea Gavana 2006-11-08
    size = dcSource.Size

    # Create a Bitmap that will later on hold the screenshot image
    # Note that the Bitmap must have a size big enough to hold the screenshot
    # -1 means using the current default colour depth
    bmp = wx.EmptyBitmap(size.width, size.height)

    # Create a memory DC that will be used for actually taking the screenshot
    memDC = wx.MemoryDC()

    # Tell the memory DC to use our Bitmap
    # all drawing action on the memory DC will go to the Bitmap now
    memDC.SelectObject(bmp)

    # Blit (in this case copy) the actual screen on the memory DC
    # and thus the Bitmap
    memDC.Blit( 0, # Copy to this X coordinate
        0, # Copy to this Y coordinate
        size.width, # Copy this width
        size.height, # Copy this height
        dcSource, # From where do we copy?
        0, # What's the X offset in the original DC?
        0  # What's the Y offset in the original DC?
        )

    # Select the Bitmap out of the memory DC by selecting a new
    # uninitialized Bitmap
    memDC.SelectObject(wx.NullBitmap)

    img = bmp.ConvertToImage()
    img.SaveFile('saved.png', wx.BITMAP_TYPE_PNG)

(我本来想直接给原文链接,但没能快速找到。)

撰写回答