NSImage drawing problems with jpgs that have a custom DPI

I ran into this problem twice now but I finally found a way of drawing a JPG which has a different pixel-size than the NSImage that represents it.

So I had an NSImage that printed like this:

NSImage 0x250390 Size={601.5, 451.5} Reps=(
		NSBitmapImageRep 0x250df0 Size={601.5, 451.5} ColorSpace=NSCalibratedRGBColorSpace 
		BPS=8 BPP=24 Pixels=802x602 Alpha=NO Planar=NO Format=0
    )

Please notice the size of {601.5, 451.5}! First I was like WTF‽ Looking for a solution I found out that the bitmap representation responds to pixelsWide and pixelsHigh, so I could use this to calculate the correct size of the image. The next problem I needed to solve was how to tell the image that it should use the correct pixel size for drawing. I tried with drawInRect:fromRect:composite:fraction to no avail.

The solution to all this mess is as simple as it could be: just set the NSImage’s size to the pixel size and you’re done!

    NSImageRep* rep = [image bestRepresentationForDevice:nil];
    NSSize imgSize = NSMakeSize([rep pixelsWide],[rep pixelsHigh]);
    [image setSize:imgSize];

These three simple lines can save a lot of trouble, especially if you don’t know about these resolution information that NSImage seems to take care of.

So thanks to this little snippet Camouflage should render wallpapers pretty much exactly as Apple does in Finder.

Karsten

One Response to “NSImage drawing problems with jpgs that have a custom DPI”

  1. Wooden Brain Says:

    I’ve been scouring the net for a solution to this problem. Most recommend basically this as a solution. However I cannot get it to work.

    Netflix seems to keep the images it stores in its RSS feeds at 300 dpi and they appear tiny in some applications, such as Growl.

    Here is an example image:

    http://cdn-0.nflximg.com/us/boxshots/small/70057002.jpg

    Please see this long thread:

    http://forums.cocoaforge.com/viewtopic.php?f=6&t=16005