0

当我的 iPad 纵向放置时,我有一个UIImage看起来方向正确的东西,但是当我得到CGImageRef与之关联的时候,它CGImageRef逆时针旋转了 90 度。经过一番谷歌搜索,我了解到这是CGImageRef因为UIImage. 我需要查看和修改 中的一些像素CGImageRef,我目前正在通过直接访问 rawData 变量(图像是 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);

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

4

1 回答 1

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);
于 2013-01-15T21:32:17.920 回答