Display NSImage from NSData

Matteo picture Matteo · Mar 14, 2011 · Viewed 7.1k times · Source

My target is to display an image in a view. Considering I've an:

  • IBOutlet NSImageView *image for display my image
  • NSData *imageData for readig the image file
  • NSImage *imageView

In imageData is stored the image (I've used initWithContentsOfFile method).

Now, if I initialize imageView with:

NSImage *imageView = [[NSImage alloc] initWithContentsOfFile:path];

I can see the rendering of the image correctly, but in this way I'm reading twice from the file system.

If I try to:

NSImage *imageView = [[NSImage alloc] initWithData:imageData];

The displayed image is very small..like thumb

Whit CGImageRef:

CGImageSourceRef imageSource = CGImageSourceCreateWithData((CFDataRef)imageData, NULL);
CGImageRef imageRef= CGImageSourceCreateImageAtIndex(imageSource, 0, nil);
NSImage *imageView = [[NSImage alloc] initWithCGImage:imageRef size:NSZeroSize];

The image is still rendering too small.

How can I display the image in original resolution?

Answer

Duncan Babbage picture Duncan Babbage · Oct 7, 2011
NSImage *imageView = [[NSImage alloc] initWithData:(NSData *)imageData];