[wxPython-users] using wxImage in C++ python extension
Robin Dunn
robin at alldunn.com
Thu Aug 17 12:01:35 PDT 2006
Christopher Barker wrote:
> I've written a tiny little factory function that creates a wx.Image with
> the data from a buffer, with a reference to the buffer. That way, the
> buffer object won't get deleted until after the wx.Image is deleted. Of
> course, as Josiah has made clear, that doesn't guarantee anything if the
> object you pass it doesn't keep that memory around, but it's a start,
> and should work at least for the common case of a simple Python string.
>
> I first thought to subclass wx.Image, and make a version that is
> identical, except that it holds a reference to the buffer object that is
> used to create it. However, I couldn't' figure out how to do it, because
> it seems wxImages are all created by different factory functions, so I
> can't just override the __init__. Can I do this with some kind of
> judicious calling of wx.Image.__new__?
>
> I've enclosed a simple test of my ImageFromBuffer function. It seems to
> work. If I don't put the reference to the string in there, I get some
> garbage. If I do, the image looks fine. would this be a worthwhile small
> addition to wxPython?
I've added it, but changed the API to be more like the other wx.Image
factories and also added the ability to specify a buffer for the alpha
channel. Does this work for you?
def ImageFromBuffer(width, height, dataBuffer, alphaBuffer=None):
"""
Creates a `wx.Image` from the data in dataBuffer. The dataBuffer
parameter must be a Python object that implements the buffer
interface, such as a string, array, etc. The dataBuffer object is
expected to contain a series of RGB bytes and be width*height*3
bytes long. A buffer object can optionally be supplied for the
image's alpha channel data, and it is expected to be width*height
bytes long.
A reference to the data and alpha buffer objects are kept with the
wx.Image, so that they won't get deleted until after the wx.Image
is deleted. However please be aware that it is not guaranteed that
an object won't move its memory buffer to a new location when it
needs to resize its contents. If that happens then the wx.Image
will end up referring to an invalid memory location and could cause
the application to crash. Therefore care should be taken to not
manipulate the objects used for the data and alpha buffers in a
way that would cause them to change size.
"""
image = wx.EmptyImage(width, height)
image.SetDataBuffer(dataBuffer)
if alphaBuffer is not None:
image.SetAlphaBuffer(alphaBuffer)
image._buffer = dataBuffer
image._alpha = alphaBuffer
return image
--
Robin Dunn
Software Craftsman
http://wxPython.org Java give you jitters? Relax with wxPython!
More information about the wxpython-users
mailing list