Our earlier tutorial, described how one can access RGBA data from a UIImage at any particular pixel coordinate.
The following code illustrates just the opposite – how does one go about constructing a UIImage from raw RGBA data.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | // //Constructing RGBA data // /*height and width are integers denoting the dimensions of the image*/ unsigned char *rawData = malloc(width*height*4); //populating rawData with pixel colour values and alpha information for (int i=0; i<width*height;++i) { rawData[4*i] = <red colour value>; rawData[4*i+1] = <green colour value>; rawData[4*i+2] = <blue colour value>; rawData[4*i+3] = 255; //alpha } /* Once we have the raw data, we convert it into a UIImage. The following code does the required work. */ CGDataProviderRef provider = CGDataProviderCreateWithData(NULL,rawData,width*height*4,NULL); int bitsPerComponent = 8; int bitsPerPixel = 32; int bytesPerRow = 4*width; CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB(); CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault; CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault; CGImageRef imageRef = CGImageCreate(width,height,8,32,4*width,colorSpaceRef,bitmapInfo,provider,NULL,NO,renderingIntent); UIImage *newImage = [UIImage imageWithCGImage:imageRef]; /* newImage is the final image that is constructed from raw RGBA data. Do remember to release the allocated parts. */ |
Please feel free to use this code in your projects.
