2013-01-15 108 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