Building Cocoa GUIs in Python with PyObjC, Part Six
Handling Images
Cocoa provides an easy interface for dealing with images, NSImage. It can be a bit tricky in Python, but once you get it right the first time, it is fairly easy. For our application we have the images stored inside the audio tags and need to populate an NSImage object from binary data stored as a Python byte-string.
There are a number of methods for initializing an NSImage object from various sources. A few of note:
initWithContentsofFile:
initWithData:
initWithPasteboard:
All of these are worth reading about in the developer documentation. We will be using initWithData:
. This accepts a NSData object to make the NSImage. This is a multiple step process, so we'll create a method to make things easier:
def buildNSImage(bytes):
data = NSData.dataWithBytes_length_(bytes, len(bytes))
return NSImage.alloc().initWithData_(data)
bytes
is a Python byte-string containing the image. NSImage will automatically handle the formatting ...