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:


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, so we don't need to worry about it. Take note that you have to run initWithData: from an existing NSImage object, which is created by calling alloc(). All of the initWith methods require an NSImage object so the NSImage.alloc() method will be used a lot.

Finally we need to connect the NSImage object to the GUI. We start by adding an Image Well (NSImageView) to our GUI, and then connect it to our object.

Image Well in GUI

QuickTag has been modified to work via Key-value coding, so in the Bindings tab of the Inspector (⌘4) we connect the Value to the appropriate key path.

Inspector Bindings tab

Finally we setup methods to handle adding or removing the image. Basically we add another sheet for images, and a method to remove the tag. These can be found in the controller.py code starting with the addImage_ method.

Now that we have the image handling QuickTag is in the final stretch. The code is available in git as usual.

Update: To get the bytes out of a NSImage takes a couple of steps:

def getBytes(nsimage):
    return nsimage.representations[0].representationUsingType_properties_(NSPNGFileType,

This takes a NSImage into a NSBitmapImageRep (subclass of NSImageRep) into a PNG held in a NSData.

<< Part5: Adding Python Modules to the Bundle

Posted: Dec 25, 2008 | Tags: python osx programming pyobjc cocoa

Comments are closed.


42 | django | python | oggify | OSCON | OSCON07 | osx | utosc | mythtv | security | reading | music | gaming | programming | tips | shell | vim | pyobjc | cocoa | iphone | blog | git


<< Dec >>
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 1 2 3 4


This space reserved for a search box

A Django site. Hosted on a Slicehost Slice