【问题标题】:Creating UIImage from context of UIImageView从 UIImageView 的上下文创建 UIImage
【发布时间】:2024-01-17 09:37:01
【问题描述】:

所以我正在使用 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

所以selectedImage 是我的UIImageView,这就是最终是白色的。任何帮助将不胜感激。

【问题讨论】:

    标签: ios iphone objective-c uiimageview uiimage


    【解决方案1】:

    也许这条线?

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

    如果您从它正上方的行中获取 UIImage,我认为您不需要以极低的 JPEG 压缩率通过它。 0 是最低质量,也许它太低以至于看起来是白色的。尝试删除该行或更改压缩。

    【讨论】:

    • 那没用,压缩不是我的问题。
    【解决方案2】:

    在这些行中

    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)];
    

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

    【讨论】:

    • 那么我应该用你给我的第三行替换前两行吗?我正在尝试获取 imageView 的可见图像。被裁剪的部分。我理解你在谈论新的上下文内容。也许我应该阅读文档;)我从解析教程中获得了0.05f。也许我应该选择0.5?我只是不希望上传时间过长并为最终用户使用大量数据。
    • 这听起来很对。你应该在上传的时候进行def压缩,我认为这只是放在一个imageView中,因此压缩会很奇怪。
    • 我可以开始聊天吗?我没有得到我期望的结果。
    • 我在使用 iPad,所以无法聊天。您将需要使用该功能手动处理屏幕比例。例如。 width * [UIScreen mainScreen].scale 和高度相同。你看到了什么问题?
    • 该代码裁剪了我的 UIImage,但我想从 UIImageView 的上下文中创建一个图像,包括如何裁剪图像。因此,当我在 imageView 中有一个图像并使用方面填充时,我想从该填充视图创建一个图像。
    【解决方案3】:

    我从这个 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;
    }
    

    【讨论】:

      最近更新 更多