Creating an NSImage from bitmap data

Brian Postow picture Brian Postow · Aug 5, 2010 · Viewed 9.4k times · Source

Ok, it appears that the I'm creating a PDFDocument where pixelWidth is incorrect in the images that I created. So the question becomes: How do I get the correct resolution into the image?

I start with bitmap data from a scanner. I'm doing this:

CGDataProviderRef provider= CGDataProviderCreateWithData(NULL (UInt8*)data, bytesPerRow * length, NULL);
CGImageRef cgImg =  CGImageCreate (
    width,
    length,
    bitsPerComponent,
    bitsPerPixel,
    bytesPerRow,
    colorspace,
    bitmapinfo, // ?        CGBitmapInfo bitmapInfo,
    provider,   //? CGDataProviderRef provider,
    NULL, //const CGFloat decode[],
    true, //bool shouldInterpolate,
    kCGRenderingIntentDefault // CGColorRenderingIntent intent
    );
/*  CGColorSpaceRelease(colorspace); */

NSData* imgData = [NSMutableData data];
CGImageDestinationRef dest = CGImageDestinationCreateWithData
    (imgData, kUTTypeTIFF, 1, NULL);
CGImageDestinationAddImage(dest, cgImg, NULL);
CGImageDestinationFinalize(dest);
NSImage* img = [[NSImage alloc] initWithData: imgData];

there doesn't appear to be anywhere in there to include the actual width/height in inches or points, nor the actual resolution, which I DO know at this point... how am I supposed to do this?

Answer

Dave DeLong picture Dave DeLong · Aug 5, 2010

If you've got a chunk of data, the easiest way to turn it into an NSImage is to use NSBitmapImageRep. Specifically something like:

NSData * byteData = [NSData dataWithBytes:data length:length];
NSBitmapImageRep * imageRep = [NSBitmapImageRep imageRepWithData:byteData];
NSSize imageSize = NSMakeSize(CGImageGetWidth([imageRep CGImage]), CGImageGetHeight([imageRep CGImage]));

NSImage * image = [[NSImage alloc] initWithSize:imageSize];
[image addRepresentation:imageRep];

...use image