user2413621
user2413621

Reputation: 2946

Share extension crashing when trying to crop very large image

I am using TOCropViewController for cropping my image. This is working fine in the main app. The problem is when I try to use this library in share extension it is not working. By not working I mean, when I try to crop a very large image (image captured on iPhone camera itself) the extension is getting crashed. As per the library developer it may be because of memory issue while trying to crop. So I tried to downscale the image before passing it to image cropper. Now the issue I am facing is that this downscaling works for few images and getting crash for others. Not sure why that is happening. The code I am using for downscaling is:

- (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize isAspectRatio:(BOOL)aspect {
    if (!image) {
        return nil;
    }
    CGFloat originRatio = image.size.width / image.size.height;
    CGFloat newRatio = newSize.width / newSize.height;

    CGSize sz;

    if (!aspect) {
        sz = newSize;
    }else {
        if (originRatio < newRatio) {
            sz.height = newSize.height;
            sz.width = newSize.height * originRatio;
        }else {
            sz.width = newSize.width;
            sz.height = newSize.width / originRatio;
        }
    }
    CGFloat scale = 1.0;
    sz.width /= scale;
    sz.height /= scale;
    UIGraphicsBeginImageContextWithOptions(sz, NO, scale);
    [image drawInRect:CGRectMake(0, 0, sz.width, sz.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

Can anyone suggest a way to downscale the image in share extension to avoid crash?

Thanks in advance.

Upvotes: 2

Views: 523

Answers (1)

ATV
ATV

Reputation: 367

You may try to use Apple's recommendation from WWDC2018:

// Downsampling large images for display at smaller size 
func downsample(imageAt imageURL: URL, to pointSize: CGSize, scale: CGFloat) -> UIImage {  
     let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary 

     let imageSource = CGImageSourceCreateWithURL(imageURL as CFURL, imageSourceOptions)! 

     let maxDimensionInPixels = max(pointSize.width, pointSize.height) * scale  
     let downsampleOptions =  [kCGImageSourceCreateThumbnailFromImageAlways: true,
     kCGImageSourceShouldCacheImmediately: true, 
     kCGImageSourceCreateThumbnailWithTransform: true,
     kCGImageSourceThumbnailMaxPixelSize: maxDimensionInPixels] as CFDictionary   
     let downsampledImage =   CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downsampleOptions)!  
     return UIImage(cgImage: downsampledImage) 
}

Upvotes: 2

Related Questions