我正在使用CIImage的ImageByCroppingToRect函数来裁剪原来是UIImage的图像。作物有效。当我做“originalImage.AsJPEG()。保存”时也可以。我已经测试并确认它保存的文件是一个有效的JPEG。但是,当我执行“croppedImage.AsJPEG()。保存”我得到一个“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);
答案 0 :(得分:1)
我认为你遇到的问题是文档中的这个注释:
我似乎记得在使用核心图像功能之前遇到这种情况,我不知道究竟是什么交易。使用核心图形进行裁剪可以正常工作:
// 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();