I have been struggling resizing an image. Basically I have stumpled upon: How to scale down a UIImage and make it crispy / sharp at the same time instead of blurry?
This seems to be a legit solution but somehow it is not working correctly.
My app works with Photos from the Camera Roll. This photos should be resized to about 200x200 whereas the width is important, not the height.
Unfortunetly I am not having a sample code as I discarded it in my rage about non working solution, sorry.
Assuming that you are referring to the layout in storyboard/IB. To get the native size of the image just select the image and press Command + = on the keyboard. the to re-size it proportionally select the corner and hold down the shift key when you re-size it.
Here is my code. The Image is in width 850 px and not 200 px:
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 } @IBAction func chooseImage(sender: AnyObject) { var myPickerController = UIImagePickerController() myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary myPickerController.delegate = self; self.presentViewController(myPickerController, animated: true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { var imagenow = info[UIImagePickerControllerOriginalImage] as? UIImage imageImage.image = resizeImage(imagenow!, newWidth: 200) pimg2 = imageImage.image! cidnew2 = textFieldCID!.text! pname2 = textFieldName!.text pmanu2 = textFieldMan!.text pnick2 = textFieldNick!.text podate2 = textFieldPODate!.text pno2 = textFieldArtNo!.text self.dismissViewControllerAnimated(true, completion: nil) }
Based on swift_dan's answer, an update for Swift 3
func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage? { let scale = newWidth / image.size.width let newHeight = image.size.height * scale UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight)) image.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With