10

I am trying to scale a image that is being graphic programmed into the photo gallery. I am trying to scale the image to make it smaller. How would I use the code below to make the image smaller

   image1.scale
  • Possible duplicate of [How do I resize the UIImage to reduce upload image size](http://stackoverflow.com/questions/29137488/how-do-i-resize-the-uiimage-to-reduce-upload-image-size) –  Mar 02 '17 at 03:13

4 Answers4

31

Use this extension to resize your image:

extension UIImage{

func resizeImageWith(newSize: CGSize) -> UIImage {

    let horizontalRatio = newSize.width / size.width
    let verticalRatio = newSize.height / size.height

    let ratio = max(horizontalRatio, verticalRatio)
    let newSize = CGSize(width: size.width * ratio, height: size.height * ratio)
    UIGraphicsBeginImageContextWithOptions(newSize, true, 0)
    draw(in: CGRect(origin: CGPoint(x: 0, y: 0), size: newSize))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage!
    }


}

Basically you are calculating the aspect ratio to keep the image intact while resizing it. Then you are getting the current image context and drawing it in the specified rectangle and finally returning it as a new image.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
fja
  • 1,823
  • 1
  • 15
  • 28
  • -some time getting black line in bottom of image . – Pankaj Gupta Dec 12 '17 at 13:45
  • bad solution for transparent image – user924 Jan 23 '18 at 13:50
  • 1
    @user924 If you want a transparent background, you should change UIGraphicsBeginImageContextWithOptions(newSize, true, 0) to UIGraphicsBeginImageContextWithOptions(newSize, false, 0) – Gefilte Fish Mar 21 '18 at 09:00
  • 1
    If you need the newSize to be the "maximum size" of the image in both axis, then you can replace `let ratio = max(horizontalRatio, verticalRatio)` with `let ratio = min(horizontalRatio, verticalRatio)`. So the new `UIImage` is never greater than width or height of `newSize` – heyfrank May 18 '18 at 09:56
4
 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 image = info[UIImagePickerControllerOriginalImage] as? UIImage
    let scaledImage:UIImage = resizeImage(image!, newWidth: 200)
    self.dismissViewControllerAnimated(true, completion: nil)

}

Swift 4 version

extension UIImage {

    func resize(withWidth newWidth: CGFloat) -> UIImage? {

        let scale = newWidth / self.size.width
        let newHeight = self.size.height * scale
        UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
        self.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage
    }
}
Politta
  • 400
  • 4
  • 10
Vinod Kumar
  • 3,375
  • 1
  • 17
  • 35
1

Try this:

First Method:

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
}

Second Method:

import UIKit

func RBSquareImageTo(image: UIImage, size: CGSize) -> UIImage {
  return RBResizeImage(RBSquareImage(image), size)
}

func RBSquareImage(image: UIImage) -> UIImage {
  var originalWidth  = image.size.width
  var originalHeight = image.size.height

  var edge: CGFloat
if originalWidth > originalHeight {
    edge = originalHeight
} else {
    edge = originalWidth
}

var posX = (originalWidth  - edge) / 2.0
var posY = (originalHeight - edge) / 2.0

var cropSquare = CGRectMake(posX, posY, edge, edge)

var imageRef = CGImageCreateWithImageInRect(image.CGImage, cropSquare);
return UIImage(CGImage: imageRef, scale: UIScreen.mainScreen().scale, orientation: image.imageOrientation)
 }

func RBResizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
let size = image.size

let widthRatio  = targetSize.width  / image.size.width
let heightRatio = targetSize.height / image.size.height

// Figure out what our orientation is, and use that to form the rectangle
var newSize: CGSize
if(widthRatio > heightRatio) {
    newSize = CGSizeMake(size.width * heightRatio, size.height * heightRatio)
} else {
    newSize = CGSizeMake(size.width * widthRatio,  size.height * widthRatio)
}

// This is the rect that we've calculated out and this is what is actually used below
let rect = CGRectMake(0, 0, newSize.width, newSize.height)

// Actually do the resizing to the rect using the ImageContext stuff
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
image.drawInRect(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

return newImage
  }

Reference:

  1. Here

  2. Here

Community
  • 1
  • 1
Sour LeangChhean
  • 7,089
  • 6
  • 37
  • 39
1

This may be helpful, this method will do proportional resizing of the image with good quality.

func resizeImage(image: UIImage, withSize: CGSize) -> UIImage {

    var actualHeight: CGFloat = image.size.height
    var actualWidth: CGFloat = image.size.width
    let maxHeight: CGFloat = withSize.width
    let maxWidth: CGFloat = withSize.height
    var imgRatio: CGFloat = actualWidth/actualHeight
    let maxRatio: CGFloat = maxWidth/maxHeight
    let compressionQuality = 0.5//50 percent compression

    if (actualHeight > maxHeight || actualWidth > maxWidth) {
        if(imgRatio < maxRatio) {
            //adjust width according to maxHeight
            imgRatio = maxHeight / actualHeight
            actualWidth = imgRatio * actualWidth
            actualHeight = maxHeight
        } else if(imgRatio > maxRatio) {
            //adjust height according to maxWidth
            imgRatio = maxWidth / actualWidth
            actualHeight = imgRatio * actualHeight
            actualWidth = maxWidth
        } else {
            actualHeight = maxHeight
            actualWidth = maxWidth
        }
    }

    let rect: CGRect = CGRect(x: 0.0, y: 0.0, width: actualWidth, height: actualHeight)
    UIGraphicsBeginImageContext(rect.size)
    image.draw(in: rect)
    let image: UIImage  = UIGraphicsGetImageFromCurrentImageContext()!
    let imageData = UIImageJPEGRepresentation(image, CGFloat(compressionQuality))
    UIGraphicsEndImageContext()

    let resizedImage = UIImage(data: imageData!)
    return resizedImage!

}

Call this methods like this,

resizeImage(image: UIImage(named: "ImageName"), withSize: CGSize(width: 300, height: 300))

Thanks:)

Karthick Selvaraj
  • 2,387
  • 17
  • 28
  • Hey, nice. However, this adds the background color to the image. – Hemang May 16 '17 at 13:32
  • it just return white background image – user924 Jan 23 '18 at 13:55
  • How to did you call this method? – Karthick Selvaraj Jan 23 '18 at 13:56
  • My image is white and it has transparent areas, you solution removes transparency (replaces it with white color), so I just got white rectangle – user924 Jan 23 '18 at 14:02
  • also your solution is worse than https://stackoverflow.com/a/42546027/7767664 quality of image isn't that good, that solution also had a problem with transparency, but I got an answer here https://stackoverflow.com/questions/48403550/resize-transparent-image-uiimage-without-getting-black-background – user924 Jan 23 '18 at 14:07