How to easily resize/optimize an image size with iOS?

后端 未结 18 1217
温柔的废话
温柔的废话 2020-11-22 11:05

My application is downloading a set of image files from the network, and saving them to the local iPhone disk. Some of those images are pretty big in size (widths larger tha

18条回答
  •  囚心锁ツ
    2020-11-22 11:32

    The above methods work well for small images, but when you try to resize a very large image, you will quickly run out of memory and crash the app. A much better way is to use CGImageSourceCreateThumbnailAtIndexto resize the image without completely decoding it first.

    If you have the path to the image you want to resize, you can use this:

    - (void)resizeImageAtPath:(NSString *)imagePath {
        // Create the image source (from path)
        CGImageSourceRef src = CGImageSourceCreateWithURL((__bridge CFURLRef) [NSURL fileURLWithPath:imagePath], NULL);
    
        // To create image source from UIImage, use this
        // NSData* pngData =  UIImagePNGRepresentation(image);
        // CGImageSourceRef src = CGImageSourceCreateWithData((CFDataRef)pngData, NULL);
    
        // Create thumbnail options
        CFDictionaryRef options = (__bridge CFDictionaryRef) @{
                (id) kCGImageSourceCreateThumbnailWithTransform : @YES,
                (id) kCGImageSourceCreateThumbnailFromImageAlways : @YES,
                (id) kCGImageSourceThumbnailMaxPixelSize : @(640)
        };
        // Generate the thumbnail
        CGImageRef thumbnail = CGImageSourceCreateThumbnailAtIndex(src, 0, options); 
        CFRelease(src);
        // Write the thumbnail at path
        CGImageWriteToFile(thumbnail, imagePath);
    }
    

    More details here.

提交回复
热议问题