c++ – Getting PixelData from CGImageRef returns wrong value

0
93


Im trying to get the Pixel-Values from a CGImageRef, but somehow it always returns the wrong values.
My Test-Image is a complete red picture, just so i can test it easier. Its this: https://i.imgur.com/ZfLtzsl.png

Im getting the CGImageRef with the following Code:

CGImageRef UICreateScreenImage();

If i add Code to save the Picture to the Album, it saves correctly a complete red screen. So the ImageRef should be correct.

IOSurfaceRef ioSurfaceRef = (__bridge IOSurfaceRef)([UIWindow performSelector:@selector(createScreenIOSurface)]);
CGImageRef cgImageRef = UICreateCGImageFromIOSurface(ioSurfaceRef);

UIImage *uiImage = [UIImage imageWithCGImage:cgImageRef];
UIImageWriteToSavedPhotosAlbum(uiImage, nil, nil, nil);

So, i found code to get the Pixel-Buffer from a ImageRef. Im using the following Code:

size_t width  = CGImageGetWidth(cgImageRef);
size_t height = CGImageGetHeight(cgImageRef);

size_t bpr = CGImageGetBytesPerRow(cgImageRef);
size_t bpp = CGImageGetBitsPerPixel(cgImageRef);
size_t bpc = CGImageGetBitsPerComponent(cgImageRef);
size_t bytes_per_pixel = bpp / bpc;
CGDataProviderRef provider = CGImageGetDataProvider(cgImageRef);
CFDataRef rawData = CGDataProviderCopyData(provider);
UInt8 * bytes = (UInt8 *) CFDataGetBytePtr(rawData); 

This gives me the width, the height, the buffer
Now, i simply loop through it and print (as test) the Pixels at [100, 100] and [100, 101], both should be red (FF0000FF)

struct SPixel {
    int r = 0;
    int g = 0;
    int b = 0;
    int a = 0;
};

for(size_t y = 0; y < height; y++) {
    for(size_t x = 0; x < width; x++) {
        const uint8_t* pixel = &bytes[y * bpr + x * bytes_per_pixel];
        SPixel Pixel;
        Pixel.a = pixel[0];
        Pixel.r = pixel[1];
        Pixel.g = pixel[2];
        Pixel.b = pixel[3];

        if(y == 100 && x == 100){
            Log::Color("red", "Pixel[100, 100]: %d, %d, %d, %d", Pixel.r, Pixel.g, Pixel.b, Pixel.a);
        }
        if(y == 100 && x == 101){
            Log::Color("red", "Pixel[100, 101]: %d, %d, %d, %d", Pixel.r, Pixel.g, Pixel.b, Pixel.a);
        }
    }
}

And now, if i let that code run, and open my complete red screenshot on fullscreen, the Pixel that get printed are the following:

Pixel[100, 100]: 147, 56, 26, 255
Pixel[100, 101]: 20, 255, 255, 144

They are complete off from Red, and are not even then same, even though they are just one pixel from each other.

What am doing wrong?