从UIImageView的上下文创建UIImage

时间:2013-12-27 20:53:43

标签: ios iphone objective-c uiimageview uiimage

所以我使用UIImageView裁剪图像,这可能会也可能不会非常有效。在图形编程方面,我有点像n00b。当我的所有代码都运行时,我遇到了白色图像,我不太清楚为什么。

我看了一眼:Crop and save visible region of UIImageView using AspectFill并没有成功。这是我的代码:

imageFile = [info objectForKey:UIImagePickerControllerOriginalImage];

selectedImage.hidden = false;  //selectedImage is my UIImageView
selectedImage.image = imageFile;

UIGraphicsBeginImageContext(selectedImage.frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGImageRef image = CGBitmapContextCreateImage(context);

float width = CGImageGetWidth(image);
float height = CGImageGetHeight(image);

CGImageRef cropped_img = CGImageCreateWithImageInRect(image, CGRectMake(0, 0, width, height));

imageFile = [UIImage imageWithCGImage:cropped_img];
imageFile = [UIImage imageWithData:UIImageJPEGRepresentation(imageFile, 0.05f)];

selectedImage.image = imageFile;  //Final product is white

所以selectedImageUIImageView,这就是白色。非常感谢任何帮助。

3 个答案:

答案 0 :(得分:0)

也许这一行?

imageFile = [UIImage imageWithData:UIImageJPEGRepresentation(imageFile, 0.05f)];

如果您从正上方的线路获取UIImage,我认为您不需要以极低的JPEG压缩率传递它。 0是最低质量,也许它看起来很低,看起来很白。尝试删除该行和/或更改压缩。

答案 1 :(得分:0)

在这些行中

CGContextRef context = UIGraphicsGetCurrentContext();
CGImageRef image = CGBitmapContextCreateImage(context);

您创建一个新的上下文,它将为空白(白色),然后从中创建一个图像。因此,您生成的图像将只是白色。

函数CGImageCreateWithImageInRect需要CGImageRef,您可以轻松地从UIImage获取

CGImageCreateWithImageInRect(imageFile.CGImage, CGRectMake(0, 0, width, height));

不确定你为什么这么做

imageFile = [UIImage imageWithData:UIImageJPEGRepresentation(imageFile, 0.05f)];

这只会给你一张质量很差的图像:/

答案 2 :(得分:0)

我从这篇SO帖子中找到了解决方案:Creating UIImage from context of UIImageView

以下是解决方案:

我需要导入Quartz Core Framework:#import <QuartzCore/QuartzCore.h>

然后我使用了以下方法:

- (UIImage*)imageFromImageView:(UIImageView*)imageView
{
    UIGraphicsBeginImageContext(imageView.frame.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextRotateCTM(context, 2*M_PI);

    [imageView.layer renderInContext:context];
    UIImage *image =  UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}