How to load a jpg file in NSBitmapImageRep?

Objective-C / Cocoa: I need to load an image from a JPG file into a two-dimensional array so that I can access each pixel. I am trying (unsuccessfully) to load an image in NSBitmapImageRep. I tried several options in 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 tried replacing the second line of code with:

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

But this gives a "incompatible type" compiler error saying that initWithData wants the NSData variable to not be NSImage.

I also tried other ways to do this, but all of them were unsuccessful either due to a compiler error or at runtime. Can someone help me with this? Ultimately, I have to upload some PNG files in the same way (so it would be nice to have a consistent method for both).

And if you know a simpler / easier way to accomplish what I'm trying to do (for example, get the images into a two-dimensional array) and not use NSBitmapImageRep, then please let me know! And by the way, I know that the path is valid (confirmed by fileExistsAtPath) - and the file name in outLabel is a file with the extension .jpg.

Thanks for any help!

+3
source share
3 answers

Easy!

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

, :

unsigned char *pixelData = [imageRep bitmapData];

(, , ), . .png.

+7

Edit:

. , - , .

:

, , . NSImage NSImageRep , . .

CGBitmapContext, . , , , .

CGImage JPG PNG , CGImageCreateWithJPEGDataProvider CGImageCreateWithPNGDataProvider .

CGContextDrawImage, , CGBitmapContextCreate, .

  • CGDataProvider .
  • CGImageRef .
  • , .
  • CGBitmapContext, .
  • .
  • .

NSImage CGImage, NSGraphicsContext CGContext graphicsContextWithGraphicsPort: flipped: . 1 2 , NSImage.

+1

imageRepWithContentsOfFile - static function

The correct way to use it is:

[NSBitmapImageRep imageRepWithContentsOfFile:filePath];
+1
source

Source: https://habr.com/ru/post/1748085/


All Articles