8

我正在尝试编辑捕获的图像并将其保存到图库。我做了

UIImagePickerController *picker=[[UIImagePickerController alloc] init];
picker.allowsEditting=YES;

我想将图像保存在可编辑的方形部分并将其保存到图库。我知道我可以[info objectForKey:@"UIImagePickerControllerEditedImage"]用来保存编辑后的图像。但这总是给我返回一个尺寸为 320x320(iPad Mini)的图像,并且图像质量很差。所以我计划[info objectForKey:@"UIImagePickerControllerOriginalImage"]使用以下代码裁剪原始图像:

CGRect rect = [[info objectForKey:@"UIImagePickerControllerCropRect"]CGRectValue];
UIImage *originalImage=[info objectForKey:@"UIImagePickerControllerOriginalImage"];
CGImageRef imageRef = CGImageCreateWithImageInRect([originalImage CGImage], rect);
UIImage *result = [UIImage imageWithCGImage:imageRef
                                      scale:originalImage.scale
                                orientation:originalImage.imageOrientation];
CGImageRelease(imageRef);

然后我保存了结果图像和编辑图像 ( [info objectForKey:@"UIImagePickerControllerEditedImage"])。当比较这两个图像时,它们很匹配。我附上了编辑和裁剪的图像。我的最终目标是将原始图像裁剪为可编辑方形部分的图像,并将其保存到具有良好图像质量的图库中。谁能告诉我这里到底出了什么问题并帮我解决这个问题?

提前致谢。裁剪图像

编辑后的图像

4

2 回答 2

2

我在这里找到了裁剪出错的原因。UIImagePickerControllerOriginalImage 返回的图像被旋转到 -90 度。所以对旋转图像进行裁剪返回给我一个不正确的裁剪图像。所以我将图像旋转了 90 度,然后将其裁剪。最后,我得到了预期的高质量裁剪图像。下面的代码解决了我的问题。

 UIImage *originalImage = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    CGRect rect=[[info objectForKey:@"UIImagePickerControllerCropRect"]CGRectValue];
    UIImage *rotatedOriginalImage=[originalImage imageRotatedByDegrees:90.0];
    CGImageRef imageRef = CGImageCreateWithImageInRect([rotatedOriginalImage CGImage], rect) ;
    UIImage *croppedImage = [UIImage imageWithCGImage:imageRef];

旋转图像的代码:

- (UIImage *)imageRotatedByDegrees:(CGFloat)degrees{
// calculate the size of the rotated view's containing box for our drawing space
UIView *rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0,0,self.size.height, self.size.width)];
CGAffineTransform t = CGAffineTransformMakeRotation(DegreesToRadians(degrees));
rotatedViewBox.transform = t;
CGSize rotatedSize = rotatedViewBox.frame.size;


// Create the bitmap context
UIGraphicsBeginImageContext(rotatedSize);
CGContextRef bitmap = UIGraphicsGetCurrentContext();

// Move the origin to the middle of the image so we will rotate and scale around the center.
CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);

//   // Rotate the image context
CGContextRotateCTM(bitmap, DegreesToRadians(degrees));

// Now, draw the rotated/scaled image into the context
CGContextScaleCTM(bitmap, 1.0, -1.0);
CGContextDrawImage(bitmap, CGRectMake(-self.size.height / 2, -self.size.width / 2, self.size.height, self.size.width), [self CGImage]);

UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
于 2013-09-13T03:49:27.707 回答
0

该错误与状态栏有关。我通过将其隐藏在 UIImagePickerController 中发现图像被正确裁剪。

快速解决方案: https ://stackoverflow.com/a/41456379

于 2018-10-10T20:02:54.450 回答