0

I have CGBitmap instance (32 bits per pixel) and I would like to get the image data in a byte[].

The byte array should get the values in ARGB format so the first 4 bytes correspond to the first pixel in the image bytes for each of the alpha, red, green and blue values.

halfer
  • 19,824
  • 17
  • 99
  • 186
SuperJMN
  • 13,110
  • 16
  • 86
  • 185
  • Check this: https://stackoverflow.com/questions/448125/how-to-get-pixel-data-from-a-uiimage-cocoa-touch-or-cgimage-core-graphics/1262893#1262893 If it's not clear enough let me know I will provide you a sample code – Yuri S Jun 20 '17 at 16:55

1 Answers1

2

Here is an idea. image is UIImage

        CGImage imageRef = image.CGImage;
        int width = (int)image.Size.Width;
        int height = (int)image.Size.Height;
        CGColorSpace colorSpace = CGColorSpace.CreateDeviceRGB();
        byte[] rawData = new byte[height * width * 4];
        int bytesPerPixel = 4;
        int bytesPerRow = bytesPerPixel * width;
        int bitsPerComponent = 8;
        CGContext context = new CGBitmapContext(rawData, width, height,
                        bitsPerComponent, bytesPerRow, colorSpace,
                        CGBitmapFlags.PremultipliedLast | CGBitmapFlags.ByteOrder32Big);

        context.DrawImage((CGRect)new CGRect(0, 0, width, height), (CGImage)imageRef);     

        // Now your rawData contains the image data in the RGBA8888 pixel format.
        int pixelInfo = (width * y + x) * 4; // The image is png
        //red,green, blue,alpha
        byte red = rawData[pixelInfo];
        byte green = rawData[pixelInfo+1];
        byte blue = rawData[pixelInfo+2];
        byte alpha = rawData[pixelInfo + 3];
Yuri S
  • 5,355
  • 1
  • 15
  • 23
  • It worked like a charm! What I don't understand is why it works, since I'm using ARGB8888, not RGBA8888. Are you sure that the bytes are sorted the way you say in your answer? – SuperJMN Jun 20 '17 at 18:20
  • OK, now it seems there is a part in your code (the last part) where you reorder the bytes. However, it's only done for one pixel (the same thing should be applied to each pixel). Isn't there a better way to do it? – SuperJMN Jun 20 '17 at 18:28
  • Maybe using the CGBitmapFlags.PremultipliedFirst is enough? – SuperJMN Jun 20 '17 at 18:30
  • I have a task to find a color of specific pixel. You can try other ways. – Yuri S Jun 20 '17 at 18:32