Search code examples
pythonwxpythonnsimageappkit

Extracting bitmap data from an NSImage in python


I'm constructing wx.MemoryDC using the data from the NSImage, but the resulting code is very sluggish. It seems to me that TIFFRepresentation -> ImageFromStream step is the one that slows things down. Is there any way to avoid this step (all this streaming), and initialize MemoryDC directly from the NSImage data? Here is the sample code:

import wx
import cStringIO
from AppKit import NSImage

app = wx.PySimpleApp()
frame = wx.Frame(None, wx.ID_ANY, "Python")
static_bitmap = wx.StaticBitmap(frame,wx.NewId(), bitmap=wx.EmptyBitmap(640, 480))
frame.Show(True)


# wget http://upload.wikimedia.org/wikipedia/commons/d/d9/Test.png
ns_image = NSImage.alloc().initWithContentsOfFile_("Test.png")

for i in range(100):

    tiffdata = ns_image.TIFFRepresentation()

    image = wx.ImageFromStream(cStringIO.StringIO(tiffdata), wx.BITMAP_TYPE_TIF)

    bitmap = image.ConvertToBitmap()

    bmdc = wx.MemoryDC(bitmap)

    # bmdc.DrawCircle(10,10, 5)
    del bmdc
    static_bitmap.SetBitmap(bitmap)


app.MainLoop()

Solution

  • Answering my own question: interface to NSIimage is inherently slow, the only workable solution is to avoid it altogether.