简体   繁体   中英

How to change the result to print the RGB pixel value in Objective C

I have this code and I want it to return the RGB colour value of each pixel, not the brightness. At the moment it prints the brightness of every pixel onto the command line and I want that to change this to print the RGB value of each pixel instead. Im fairly new to Objective-C so some help and explanation would be greatly appreciated :).

An example of what I have so far. This image shows the brightness of each pixel

 // 1. Get pixels of image
  CGImageRef inputCGImage = [image CGImage];
  NSUInteger width = CGImageGetWidth(inputCGImage);
  NSUInteger height = CGImageGetHeight(inputCGImage);

  NSUInteger bytesPerPixel = 4;
  NSUInteger bytesPerRow = bytesPerPixel * width;
  NSUInteger bitsPerComponent = 8;

  UInt32 * pixels;
  pixels = (UInt32 *) calloc(height * width, sizeof(UInt32));

  CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
  CGContextRef context = CGBitmapContextCreate(pixels, width, height,
                                               bitsPerComponent, bytesPerRow, colorSpace,
                                               kCGImageAlphaPremultipliedLast|kCGBitmapByteOrder32Big);

  CGContextDrawImage(context, CGRectMake(0, 0, width, height), inputCGImage);

  CGColorSpaceRelease(colorSpace);
  CGContextRelease(context);

#define Mask8(x) ( (x) & 0xFF )
#define R(x) ( Mask8(x) )
#define G(x) ( Mask8(x >> 8 ) )
#define B(x) ( Mask8(x >> 16) )

  // 2. Iterate and log!
  NSLog(@"Brightness of image:");
  UInt32 * currentPixel = pixels;
  for (NSUInteger j = 0; j < height; j++) {
    for (NSUInteger i = 0; i < width; i++) {
      UInt32 color = *currentPixel;

      printf("%3.0f ", (R(color)+G(color)+B(color))/3.0);
      currentPixel++;
    }
    printf("\n");
  }

  free(pixels);

Just change this line:

printf("%3.0f ", (R(color)+G(color)+B(color))/3.0);

to

printf("(r=%3.0f, g=%3.0f, b=%3.0f) ", R(color), G(color), B(color));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM