8.3 C
New York
Wednesday, March 19, 2025

ios – CGImage to vImage buffer conversion results in improper colours


I’m changing an UIImage to a Vimage_Buffer. The code appears to be like as follows:

    CGImageRef originalImageRef = [image CGImage];
    CGColorSpaceRef originalColorSpace = CGImageGetColorSpace(originalImageRef);
    CGColorRenderingIntent intent = CGImageGetRenderingIntent(originalImageRef);
    
    vImage_CGImageFormat inputImageFormat =
    {
        .bitsPerComponent = (uint32_t) CGImageGetBitsPerComponent(originalImageRef),
        .bitsPerPixel = (uint32_t) CGImageGetBitsPerComponent(originalImageRef) * (uint32_t)(CGColorSpaceGetNumberOfComponents(originalColorSpace) + (kCGImageAlphaNone != CGImageGetAlphaInfo(originalImageRef))),
        .colorSpace = originalColorSpace,
        .bitmapInfo = CGImageGetBitmapInfo(originalImageRef),
        .model = 0,
        .decode = NULL,
        .renderingIntent = kCGRenderingIntentDefault
    };
    
    vImage_Error error = vImageBuffer_InitWithCGImage(inputImageBuffer, &inputImageFormat, NULL, originalImageRef, kvImageNoFlags);
    if (error  == kvImageNoError) {
        NSLog(@"picture to vimage buffer conversion full");
    } else {
        NSLog(@"picture to vimage buffer conversion failed");
    }

However the ensuing buffer colours are all completely different. All of the Blue tones develop into Yellow and so forth. I attempted the next code as properly:

   CGImageRef sourceRef = [image CGImage];
   NSUInteger sourceWidth = CGImageGetWidth(sourceRef);
   NSUInteger sourceHeight = CGImageGetHeight(sourceRef);

   CGDataProviderRef supplier = CGImageGetDataProvider(sourceRef);
   CFDataRef bitmapData = CGDataProviderCopyData(supplier);

   unsigned char *sourceData = (unsigned char*)calloc(sourceHeight * sourceWidth * 4, sizeof(unsigned char));
   NSUInteger bytesPerPixel = 4;
   NSUInteger sourceBytesPerRow = bytesPerPixel * sourceWidth;

   CFDataGetBytes(bitmapData, CFRangeMake(0, CFDataGetLength(bitmapData)), sourceData);

   vImage_Buffer v_image = {
       .information = (void *)sourceData,
       .top = sourceHeight,
       .width = sourceWidth,
       .rowBytes = sourceBytesPerRow
   };

   CFRelease(bitmapData);

However this additionally appears to have identical downside. Any assist on this regard is very appreciated.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles