Our iphone application ArtMaestro, reads RGB data from a UIImage.
The following function illustrates how to read RGBA data from a UIImage.
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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | -(void) readImage:(UIImage*)inputImage { CGImageRef inImage = [inputImage CGImage]; //height of input image int ht = CGImageGetWidth(inImage); //width of input image int wdth = CGImageGetHeight(inImage); //determine colour space CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); //Array to store RGB values unsigned char *rawData = malloc(ht*wdth*4); //input image characteristics NSUInteger bytesPerRowImg = CGImageGetBytesPerRow(inImage); NSUInteger bitsPerComponentImg = CGImageGetBitsPerComponent(inImage); NSUInteger bitsPerPixelImg = CGImageGetBitsPerPixel(inImage); //create CGContext CGContextRefcontext=CGBitmapContextCreate(rawData,ht,wdth,bitsPerComponentImg,bytesPerRowImg,colorSpace,kCGImageAlphaPremultipliedLast| kCGBitmapByteOrder32Big); // One might change these parameters - // kCGImageAlphaPremultipliedLast| kCGBitmapByteOrder32Big // This depends upon RGBA/ ARGB (location of alpha) // and other parameters //free the colorspace CGColorSpaceRelease(colorSpace); CGContextDrawImage(context,CGRectMake(0,0,wdth,ht), inImage); //release CGImage CFRelease(inImage); //release context CGContextRelease(context); int byteIndex = 0; //Copy RGB values into rawData for(int i = 0;i < count; ++i) { Byte redColour = rawData[byteIndex]; Byte greenColour = rawData[byteIndex+1]; Byte blueColour = rawData[byteIndex+2]; CGFloat alphaColour = rawData[byteIndex + 3]/255.0f; //would also depend upon CGBitmapInfo of the input image byteIndex +=4; } /* The array rawData now contains the RGB values You might use these values for you image processing projects. Make sure you free this after your work */ /// // Your RGBA manipulation code goes here // To access the RGBA data at a particular pixel (xCor,yCor) // int redValueAtPixel = rawData[wdth*yCor+xCor]; // int greenValueAtPixel = rawData[wdth*yCor+xCor+1]; // int blueValueAtPixel = rawData[wdth*yCor+xCor+2]; // float alphaAtPixel = rawData[wdth*yCor+xCor+3]x255.0f; /// free(rawData); } |
Please feel free to use this code in your projects.
Happy Coding
Tags: iphone development, Objective C, UIImage
