Pages

June 14, 2013

ARGB raw data from bitmap

This is not a simple nor straightforward method, because it involves CGImageRef, CGContextRef and raw image data manipulation.
But what it's actually doing is very clear: it takes an image and create its ARGB rappresentation.



/** Create an ARGB Bitmap from image.

 @param image CGImageRef of original image.
 @return Returns the CGContextRef of a Bitmap representing the image.

 */
+ (CGContextRef)createARGBBitmapContextFromImage:(CGImageRef)image {

    CGContextRef context = NULL;
    CGColorSpaceRef colorSpace;
    void *bitmapData;
    int bitmapByteCount;
    int bitmapBytesPerRow;

    // Get image width and height. We'll use the entire image.
    size_t pixelsWide = 1;
    size_t pixelsHigh = 1;

    // Declare the number of bytes per row. Each pixel in the bitmap is represented by 4 bytes; 8 bits each of red, green, blue, and alpha.
    bitmapBytesPerRow    = (pixelsWide * 4);
    bitmapByteCount        = (bitmapBytesPerRow * pixelsHigh);

    // Use the generic RGB color space.
    colorSpace = CGColorSpaceCreateDeviceRGB();
    if (colorSpace == NULL) {
        fprintf(stderr, "Error allocating color space");
        return NULL;
    }

    // Allocate memory for image data. This is the destination in memory where any drawing to the bitmap context will be rendered.
    bitmapData = malloc(bitmapByteCount);
    if (bitmapData == NULL) {
        fprintf (stderr, "Memory not allocated!");
        CGColorSpaceRelease(colorSpace);
        return NULL;
    }

    // Create the bitmap context. We want pre-multiplied ARGB, 8-bits per component.
    // Regardless of what the source image format is (CMYK, Grayscale, ...) it will be converted over to the format specified here by CGBitmapContextCreate.
    context = CGBitmapContextCreate (bitmapData,
                                     pixelsWide,
                                     pixelsHigh,
                                     8, // Bits per component.
                                     bitmapBytesPerRow,
                                     colorSpace,
                                     kCGImageAlphaPremultipliedFirst);
    if (context == NULL) {
        free (bitmapData);
        fprintf (stderr, "Context not created!");
    }

    // Release colorspace before returning.
    CGColorSpaceRelease(colorSpace);

    return context;
}




Download the ready-for-use source file (.m) of ARGB raw data from bitmap

No comments:

Post a Comment