AsJPEG().将CIImage转换为UIImage后保存不起作用

本文关键字:UIImage 保存 不起作用 转换 CIImage AsJPEG | 更新日期: 2023-09-27 17:57:49

我正在使用CIImage的ImageByCroppingToRect函数来裁剪一个最初是UIImage的图像。作物有效。当我做一个"originalImage.AsJPEG().Save"时,它也同样有效。我已经测试并确认它保存的文件是一个工作JPEG。但是,当我执行"croppedImage.AsJPEG().Save"时,我会在其行中出现"System.NullReferenceException:对象引用未设置为对象实例"错误。originalImage和croppedImage都是UIImages,唯一的区别是croppedImages源于进行裁剪的转换后的CIImage。。。但为什么会导致这个错误呢?这是一个UIImage,所以它应该可以工作,对吧?我知道croppedImage中的图像之所以存在,是因为我将图像输出到屏幕上的行"view.image=croppedImage;",这样我就可以看到裁剪效果了。

以下是源代码,此链接是包含jpg图像的实际项目:https://www.dropbox.com/s/erh0yrew8pyuye7/TestImageCrop.zip

        // Create an image from a file
        UIImage originalImage = UIImage.FromFile("IMG_0072.jpg");
        // Create a UIImageView
        UIImageView view = new UIImageView(new RectangleF(0,0,300,300));
        this.View.AddSubview(view);
        // Crop the image using CIImage's ImageByCroppingToRect function
        CIImage testCIImage = new CIImage(originalImage).ImageByCroppingToRect(new RectangleF(0,0,500,500));
        UIImage croppedImage = new UIImage(testCIImage);
        view.Image = croppedImage;

        // Store the image to a file
        string Path = Environment.GetFolderPath ( Environment.SpecialFolder.MyDocuments ) + "/";
        NSError err = new NSError();
        originalImage.AsJPEG().Save(Path+"originalImage.jpg", true, out err);
        // Here is where the error is happening.  If I save the originalImage as a JPEG, it works just fine.
        // But if I save the croppedImage as a JPEG, it errors out saying "System.NullReferenceException: Object reference not set to an instance of an object" 
        croppedImage.AsJPEG().Save(Path+"croppedImage.jpg", true, out err);

AsJPEG().将CIImage转换为UIImage后保存不起作用

我认为您遇到的问题是文档中的以下注释:

如果图像没有数据,或者底层CGImageRef包含不支持的位图格式的数据,则此函数可能返回nil

我似乎记得在使用核心图像功能之前遇到过这个问题,我不知道具体是什么。使用核心图形进行裁剪效果很好:

    // crop using core graphics instead of CIImage
    SizeF newSize = new SizeF(500,500);
    UIGraphics.BeginImageContextWithOptions(size:newSize, opaque:false, scale:0.0f);
    originalImage.Draw (new RectangleF(0,0,originalImage.Size.Width,originalImage.Size.Height));
    UIImage croppedImage = UIGraphics.GetImageFromCurrentImageContext();
    UIGraphics.EndImageContext();