Resize UIImage in Swift and iOS 8

Here is an extension to UIImage that adds a public method called resize(size:CGSize, completionHandler:(resizedImage:UIImage, data:NSData)->()). The image is resized on a global concurrent queue and the completion handler is called on the main queue with the new UIImage and image data. Good for resizing images before sending them to a server. The jpeg compression ratio should probably also be parameterized! Enjoy!


extension UIImage {
    public func resize(size:CGSize, completionHandler:(resizedImage:UIImage, data:NSData)->()) {
        dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), { () -> Void in
            var newSize:CGSize = size
            let rect = CGRectMake(0, 0, newSize.width, newSize.height)
            UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
            self.drawInRect(rect)
            let newImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            let imageData = UIImageJPEGRepresentation(newImage, 0.5)
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                completionHandler(resizedImage: newImage, data:imageData)
            })
        })
    }
}

7 thoughts on “Resize UIImage in Swift and iOS 8”

  1. Create a swift extension file and paste it into there.

    Then you can call it like this, usually from a UImagePickerController delegate method:

    image.resize(CGSizeMake(150, 150), completionHandler: { [weak self](resizedImage, data) -> () in

    let image = resizedImage

    self?.imageView.image = image

    self?.viewModel.imageData = data

    })

  2. Erril, I haven’t ran the profiler against it but since the drawing is being done in a background thread the UI thread hums along just fine while resizing even very large images.

  3. Thanks for the response. I think this will help a lot. What i’m trying to do is take an image and create 3 different sizes. Thumbnail, small, medium. Then I want to save it to something like parse. Since it’s done in the background, I have to find a way to make the operations serial. I’ll have to think about this. Thanks however

  4. Erril, you can just nest the callbacks, but if that’s too difficult to read you can use a promises implementation like PromiseKit. Swift also supports variadic functions so you can change the method to accept as well as return multiple images in the callback.

    http://promisekit.org/

  5. thanks for your help. i looked at promisekit and it’s quite vague. looks like it only caters to a few ui controls/functions. I don’t think i’m explaining my issue properly. thanks for your input hower

Leave a Reply

Your email address will not be published. Required fields are marked *