Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize UIImage to 200x200pt/px

Tags:

ios

swift

uiimage

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.

like image 569
swift_dan Avatar asked Aug 12 '15 13:08

swift_dan


People also ask

How do I make an image smaller in Xcode?

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.


2 Answers

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)  } 
like image 173
swift_dan Avatar answered Oct 07 '22 05:10

swift_dan


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 } 
like image 39
Christoph R Avatar answered Oct 07 '22 04:10

Christoph R