문제

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:

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

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:

    // 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();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top