如何旋转图像文件?

时间:2011-05-19 11:59:42

标签: iphone cocoa-touch image file rotation

如何轻松旋转保存在文档目录中的图像文件?

我用代码保存它:

(...)
UIImage *capturedImage = UIGraphicsGetImageFromCurrentImageContext();
NSData* imageData = UIImageJPEGRepresentation(capturedImage, 1.0);
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
[imageData writeToFile:[docDir stringByAppendingPathComponent:@"saved.jpg"] atomically:NO];
UIGraphicsEndImageContext();

1 个答案:

答案 0 :(得分:2)

使用CGContextRotateCTM()轻松完成:

在SO答案中找到:How to Rotate a UIImage 90 degrees?

static inline double radians (double degrees) {return degrees * M_PI/180;}
- (UIImage*) rotateImage:(UIImage*)src rotationDirection:(UIImageOrientation)orientation {
    UIGraphicsBeginImageContext(src.size);

    CGContextRef context(UIGraphicsGetCurrentContext());
    if (orientation == UIImageOrientationRight) {
        CGContextRotateCTM (context, radians(90));
    } else if (orientation == UIImageOrientationLeft) {
        CGContextRotateCTM (context, radians(-90));
    } else if (orientation == UIImageOrientationDown) {
        // NOTHING
    } else if (orientation == UIImageOrientationUp) {
        CGContextRotateCTM (context, radians(90));
    }

    [src drawAtPoint:CGPointMake(0, 0)];

    return UIGraphicsGetImageFromCurrentImageContext();
}