Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an NSImage from bitmap data

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?

like image 606
Brian Postow Avatar asked Dec 10 '22 14:12

Brian Postow


1 Answers

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
like image 59
Dave DeLong Avatar answered Dec 30 '22 13:12

Dave DeLong