Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load JPG file into NSBitmapImageRep?

Objective-C / Cocoa: I need to load the image from a JPG file into a two dimensional array so that I can access each pixel. I am trying (unsuccessfully) to load the image into a NSBitmapImageRep. I have tried several variations on the following two lines of code:

NSString *filePath = [NSString stringWithFormat: @"%@%@",@"/Users/adam/Documents/phoneimages/", [outLabel stringValue]];  //this coming from a window control
NSImageRep *controlBitmap = [[NSImageRep alloc] imageRepWithContentsOfFile:filePath];

With the code shown, I get a runtime error: -[NSImageRep imageRepWithContentsOfFile:]: unrecognized selector sent to instance 0x100147070.

I have tried replacing the second line of code with:

NSImage *controlImage = [[NSImage alloc] initWithContentsOfFile:filePath];
NSBitmapImageRep *controlBitmap = [[NSBitmapImageRep alloc] initWithData:controlImage];

But this yields a compiler error 'incompatible type' saying that initWithData wants a NSData variable not an NSImage.

I have also tried various other ways to get this done, but all are unsuccessful either due to compiler or runtime error. Can someone help me with this? I will eventually need to load some PNG files in the same way (so it would be nice to have a consistent technique for both).

And if you know of an easier / simpler way to accomplish what I am trying to do (i.e., get the images into a two-dimensional array), rather than using NSBitmapImageRep, then please let me know! And by the way, I know the path is valid (confirmed with fileExistsAtPath) -- and the filename in outLabel is a file with .jpg extension.

Thanks for any help!

like image 315
Adam Avatar asked Jan 29 '26 08:01

Adam


1 Answers

Easy!

NSImage *controlImage = [[NSImage alloc] initWithContentsOfFile:filePath];
NSBitmapImageRep *imageRep = [[controlImage representations] objectAtIndex:0];

Then to get the actual bitmap pixel data:

unsigned char *pixelData = [imageRep bitmapData];

If your image has multiple representations (it probably doesn't), you can get them out of that same array. The same code will work for your .png images.

like image 193
Carl Norum Avatar answered Jan 31 '26 01:01

Carl Norum