There’s already a lot of stuff about image resizing on iOS already available on the web with each discussing about potential pros and cons of the technique. There is also a good post on NSHipster summarizing some of the best available image resizing techniques.
With iOS 8, Apple has given us PhotoKit
, a modern framework for managing photos without diving into the low level details and more performant than AssetsLibrary. Let’s see how we can resize a simple image selected using the UIImagePickerController
using PhotoKit.
imagePickerController.bk_didFinishPickingMediaBlock = {
(controller imagePickerController: UIImagePickerController!, dictionary: [NSObject:AnyObject]!) -> Void in
imagePickerController.dismissViewControllerAnimated(true, completion: nil)
guard let assetURL = dictionary[UIImagePickerControllerReferenceURL] as? NSURL else {
if let image = dictionary[UIImagePickerControllerOriginalImage] as? UIImage {
// TODO Image taken from the camera. Resize using one of the techniques discussed on https://nshipster.com/image-resizing/
}
return
}
// Fetch Photos Asset and resize image
let fetchResult = PHAsset.fetchAssetsWithALAssetURLs([assetURL], options: nil)
let options = PHImageRequestOptions()
options.synchronous = false
options.resizeMode = .Fast
options.deliveryMode = .HighQualityFormat
guard let asset = fetchResult.firstObject as? PHAsset else {
if let image = dictionary[UIImagePickerControllerOriginalImage] as? UIImage {
// TODO Cannot find the associated PhotoKit asset. Resize using one of the techniques discussed on https://nshipster.com/image-resizing/
}
return
}
// Request resized image
PHImageManager.defaultManager().requestImageForAsset(asset, targetSize: CGSize(width: 1024, height: 1024), contentMode: .AspectFit, options: options, resultHandler: { (image, _) -> Void in
// image is the resized image
})
}
The code is pretty straightforward. We fetch the PHAsset
from the asset url of the image and then use the PHImageManager
to get the resized image. There are a few options to control the scaling mode.
deliveryMode
: Controls the requested image quality and delivery priority.Opportunistic
: Photos automatically provides one or more results in order to balance image quality and responsiveness. The resultHandler block more than once with different quality images as they become available.HighQualityFormat
: Photos provides only the highest-quality image available, regardless of how much time it takes to load.FastFormat
: Photos provides only a fast-loading image, possibly sacrificing image quality.resizeMode
: A mode that specifies how to resize the requested image.None
: Photos does not resize the image asset.Fast
: Photos efficiently resizes the image to a size similar to, or slightly larger than, the target size.Exact
: Photos resizes the image to match the target size exactly.