2013-01-15 152 views
0

我有一个UIImage,当我的iPad保持纵向显示时,它看起来是正确的方式,但是当我得到CGImageRef与之关联时,CGImageRef逆时针旋转90度。谷歌搜索后,我知道这是因为CGImageRef没有方向数据,不像UIImage。我需要查看和修改一些像素在CGImageRef,目前我在做这个通过直接访问RAWDATA变量(图像是一个UIImage *):如何旋转CGImageRef?

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); 

但是,为了让我正常修改rawData中存储的像素数据,我需要CGImageRef处于正确的方向。如何顺时针旋转CGImageRef 90度然后访问rawData(像素信息)?

回答

0

试试这个:

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); 
+0

为什么目标的高度和宽度需要翻转左/右方向?另外,为什么位图需要翻译? – Mahir

+2

bitmapInfo从哪里来?你应该也可以释放CGContextRef。 – sdsykes