CGImage from byte array

后端 未结 3 1651
栀梦
栀梦 2020-12-05 02:58

Loading a CGImage or NSImage from a file using a standard image format (jpeg, gif, png et.) is all very simple.

However, I now need to create a CGImage from an arra

3条回答
  •  無奈伤痛
    2020-12-05 03:41

    Using CFData can make the above code simpler. Here is the code.

    // raw pixel data memory of 64 * 64 pixel size
    
    UInt8 pixelData[64 * 64 * 3];
    
    // fill the raw pixel buffer with arbitrary gray color for test
    
    for(size_t ui = 0; ui < 64 * 64 * 3; ui++)
      pixelData[ui] = 210;
    
    CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
    
    CFDataRef rgbData = CFDataCreate(NULL, pixelData, 64 * 64 * 3);
    
    CGDataProviderRef provider = CGDataProviderCreateWithCFData(rgbData);
    
    CGImageRef rgbImageRef = CGImageCreate(64, 64, 8, 24, 64 * 3, colorspace, kCGBitmapByteOrderDefault, provider, NULL, true, kCGRenderingIntentDefault); 
    
    CFRelease(rgbData);
    
    CGDataProviderRelease(provider);
    
    CGColorSpaceRelease(colorspace);
    
    // use the created CGImage
    
    CGImageRelease(rgbImageRef);
    

提交回复
热议问题