0

I have a UIImage that appears to be oriented the correct way when my iPad is held in portrait, but when I get the CGImageRef associated with it, the CGImageRef is rotated 90 degrees counterclockwise. After some Googling, I've learned that this is because the CGImageRef has no orientation data unlike the UIImage. I need to view and modify some of the pixels in the CGImageRef, and I'm currently doing this by directly accessing the rawData variable (image is a UIImage*):

CGImageRef imageRef = [image CGImage];

CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB(); //maybe make ...Gray();
unsigned char *rawData = (unsigned char*) calloc(height * width * 4, sizeof(unsigned char));
CGContextRef context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent, bytesPerRow, colorSpaceRef, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);

CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);

However, in order for me to properly modify the pixel data stored in rawData, I need the CGImageRef to be in the correct orientation. How can I rotate the CGImageRef 90 degrees clockwise and then access rawData (the pixel information)?

Jean-Philippe Bond
  • 10,089
  • 3
  • 34
  • 60
sghodas
  • 28
  • 2
  • 8

1 Answers1

0

try this :

CGImageRef imageRef = [sourceImage CGImage];
CGColorSpaceRef colorSpaceInfo = CGImageGetColorSpace(imageRef);


CGContextRef bitmap;

if (sourceImage.imageOrientation == UIImageOrientationUp || sourceImage.imageOrientation == UIImageOrientationDown) {
    bitmap = CGBitmapContextCreate(NULL, targetWidth, targetHeight, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpaceInfo, bitmapInfo);

} else {
    bitmap = CGBitmapContextCreate(NULL, targetHeight, targetWidth, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpaceInfo, bitmapInfo);

}   

if (sourceImage.imageOrientation == UIImageOrientationLeft) {
    CGContextRotateCTM (bitmap, radians(90));
    CGContextTranslateCTM (bitmap, 0, -targetHeight);

} else if (sourceImage.imageOrientation == UIImageOrientationRight) {
    CGContextRotateCTM (bitmap, radians(-90));
    CGContextTranslateCTM (bitmap, -targetWidth, 0);

} else if (sourceImage.imageOrientation == UIImageOrientationUp) {
    // NOTHING
} else if (sourceImage.imageOrientation == UIImageOrientationDown) {
    CGContextTranslateCTM (bitmap, targetWidth, targetHeight);
    CGContextRotateCTM (bitmap, radians(-180.));
}

CGContextDrawImage(bitmap, CGRectMake(0, 0, targetWidth, targetHeight), imageRef);
CGImageRef ref = CGBitmapContextCreateImage(bitmap);
oiledCode
  • 8,589
  • 6
  • 43
  • 59
  • Why does the target height and width need to be flipped for left/right orientations? Also, why does the bitmap need to be translated? – Mahir May 02 '13 at 03:15
  • 2
    Where does bitmapInfo come from? You should probably release the CGContextRef also. – sdsykes Jun 25 '14 at 09:40