swiftswift3core-imagecgsize

In Swift 3, How to change the resolution on the selected image in Pickerview Controller


The resolution of the original image selected in imagePickerControllerd is 2448x3264.

I want to keep the ratio and change the resolution.

I need help.


Solution

  • func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [AnyHashable: Any]!) {
        dPrint("IMAGE DICT>> \(editingInfo)")
        self.dismiss(animated: true, completion: nil)
    
        var cropImage : UIImage?
    
        if image.size.width > 300 || image.size.height > 300
        {
            cropImage = self.imageWithImage(image: image, scaledToSize: CGSize(width: 300.0, height: 300.0))
        }
        else{
            cropImage = image
        }
    
      let lowResolutionImg =  cropImage?.lowestQualityJPEGNSData as Data!
    }
    func imageWithImage(image:UIImage ,scaledToSize newSize:CGSize)-> UIImage
        {
            UIGraphicsBeginImageContext( newSize )
            image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
            let newImage : UIImage = UIGraphicsGetImageFromCurrentImageContext()!;
            UIGraphicsEndImageContext();
            return newImage
        }
    //MARK:- EXTENSION FOR UIIMAGE
    extension UIImage {
        var uncompressedPNGData: Data      { return UIImagePNGRepresentation(self)!        }
        var highestQualityJPEGNSData: Data { return UIImageJPEGRepresentation(self, 1.0)!  }
        var highQualityJPEGNSData: Data    { return UIImageJPEGRepresentation(self, 0.75)! }
        var mediumQualityJPEGNSData: Data  { return UIImageJPEGRepresentation(self, 0.5)!  }
        var lowQualityJPEGNSData: Data     { return UIImageJPEGRepresentation(self, 0.25)! }
        var lowestQualityJPEGNSData:Data   { return UIImageJPEGRepresentation(self, 0.0)!  }
    }