I’m using CIImage’s ImageByCroppingToRect function to crop an image that’s originally a UIImage. The crop works. When I do a “originalImage.AsJPEG().Save” that works as well. I’ve tested and confirmed that the file it saves is a working JPEG. But when I do a “croppedImage.AsJPEG().Save” I get a “System.NullReferenceException: Object reference not set to an instance of an object” error on its line. Both originalImage and croppedImage are UIImages, the only difference is that croppedImage originated from a converted CIImage that did the crop… but why would that cause this error? It’s a UIImage so it should work, right? And I know the image in croppedImage exists because of the line “view.Image = croppedImage;” where I outputted the image to the screen so I can see that the crop worked.
Below is the source code and this link is the actual project including the jpg image: 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);
I think the problem you’re running into is this note in the docs:
I seem to remember running into this before using core image functions, I don’t know exactly what the deal is. Using core graphics to crop instead works fine: