Search code examples
iosswiftuiimagepickercontrollerimage-resizing

How to resize photo with UIImagePicker / Swift


I am having trouble resizing a photo after the camera takes the photo in swift. Currently I have an Image View in my scene that is 100 x 100 (for a profile photo) but when I run the app, the photo never shows up after I use the camera. Here is my code. What I am missing:

@IBAction func employeePhotoButton(sender: AnyObject) {

    if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) {
        var imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = UIImagePickerControllerSourceType.Camera;
        imagePicker.allowsEditing = false
        self.presentViewController(imagePicker, animated: true, completion: nil)

        func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage {

            let scale = newWidth / image.size.width
            let newHeight = image.size.height * scale
            UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight))
            image.drawInRect(CGRectMake(0, 0, newWidth, newHeight))
            let newImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()

            return newImage
        }

        func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {

            employeePhoto.image = resizeImage(image!, newWidth: 100)

            self.dismissViewControllerAnimated(true, completion: nil);
        }


    }
}

Solution

  • Try something like this (Note this is using Swift3 syntax):

    // your IBAction could look something like this
    @IBAction func employeePhotoButton(sender: AnyObject) 
    {
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) 
        {
            showImagePicker(.camera)
        }
        else
        {
            print("camera not available")
        }
    }
    
    // your function in your view controller to display the image picker with whichever
    // source type you want, check for source type availability before calling
    func showImagePicker(sourceType:UIImagePickerControllerSourceType)
    {
        // instantiates and configures class var
        self.imagePickerController = UIImagePickerController.init()
        self.imagePickerController?.modalPresentationStyle = .currentContext
        self.imagePickerController?.sourceType = sourceType
        self.imagePickerController?.delegate = self
        self.imagePickerController?.allowsEditing = false
    
        // present controller
        self.present(self.imagePickerController!, animated: true, completion: nil)
    }
    
    
    // Image picker delegate function
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
    {
        // dismiss the picker view controller
        print("Selected media with info: \(info)")
        self.dismiss(animated: true, completion: nil)
    
        // no longer need this so nil out now
        self.imagePickerController = nil
    
        // check our image is valid
        guard (info[UIImagePickerControllerOriginalImage] != nil) else {
            print("No image found to load...")
            return
        }
    
        // sets our 'selectedImg' class var for use elsewhere if needed
        selectedImg = info[UIImagePickerControllerOriginalImage] as? UIImage
    
        // verify the image is not nil
        guard selectedImg != nil  else {
            print("selected image is nil")
            return
        }
    
        // resize our selected image
        let resizedImage = selectedImg.convert(toSize:CGSize(width:100.0, height:100.0), scale: UIScreen.main.scale)
    
        // TODO: whatever you want to do with your resized image
        employeePhoto.image = resizedImage
    }
    
    
    extension UIImage
    {
        // convenience function in UIImage extension to resize a given image
        func convert(toSize size:CGSize, scale:CGFloat) ->UIImage
        {
            let imgRect = CGRect(origin: CGPoint(x:0.0, y:0.0), size: size)
            UIGraphicsBeginImageContextWithOptions(size, false, scale)
            self.draw(in: imgRect)
            let copied = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
    
            return copied!
        }
    }