【问题标题】:AsJPEG().Save not working after converting CIImage to UIImage将 CIImage 转换为 UIImage 后,AsJPEG().Save 不起作用
【发布时间】:2013-02-04 16:35:12
【问题描述】:

我正在使用 CIImage 的 ImageByCroppingToRect 函数来裁剪最初是 UIImage 的图像。庄稼起作用了。当我执行“originalImage.AsJPEG().Save”时也可以。我已经测试并确认它保存的文件是工作 JPEG。但是,当我执行“croppedImage.AsJPEG().Save”时,我在其行上收到“System.NullReferenceException:对象引用未设置为对象的实例”错误。 originalImage 和croppedImage 都是UIImages,唯一的区别是croppedImage 来自于经过裁剪的转换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);

【问题讨论】:

    标签: c# xamarin.ios crop core-image ciimage


    【解决方案1】:

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

    This function may return nil if the image has no data or if the underlying CGImageRef contains data in an unsupported bitmap format

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

        // 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();
    

    【讨论】:

    • 所以我的裁剪框将由 originalImage.Draw 参数中新 RectF 的 X 和 Y 坐标以及 newSize 中的宽度和高度值组成?谢谢。这看起来不错,我会实现它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-06
    • 1970-01-01
    • 2012-01-15
    • 1970-01-01
    • 1970-01-01
    • 2017-08-30
    • 1970-01-01
    相关资源
    最近更新 更多