Stanley Stanley - 2 months ago 25
iOS Question

Confused about UIImage's init(data:scale:) method in Swift 3.0

Here is my purpose, I have an image width of 750 and I want to scale it to 128
Then I found an init method of UIImage called
init(data:scale:)

The next is my code

func scaleImage(image:UIImage, ToSpecificWidth targetWidth:Int) -> UIImage{
var scale = Double(targetWidth) / Double(image.size.width)
let scaledImage = UIImage(data: UIImagePNGRepresentation(image)! as Data, scale: CGFloat(scale))
return scaledImage!
}

print("originImageBeforeWidth: \(portrait?.size.width)") // output: 750
let newImage = Tools.scaleImage(image: portrait!, ToSpecificWidth: 128) // the scale is about 0.17
print("newImageWidth: \(newImage.size.width)") // output: 4394.53125


apparently the new width is too far away from my intension
I'm looking for 750 * 0.17 = 128
But I get 750 / 0.17 = 4394

then I change my scaleImage func
Here is the updated code

func scaleImage(image:UIImage, ToSpecificWidth targetWidth:Int) -> UIImage{
var scale = Double(targetWidth) / Double(image.size.width)
scale = 1/scale // new added
let scaledImage = UIImage(data: UIImagePNGRepresentation(image)! as Data, scale: CGFloat(scale))
return scaledImage!
}

print("originImageBeforeWidth: \(portrait?.size.width)") // output: 750
let newImage = Tools.scaleImage(image: portrait!, ToSpecificWidth: 128) // the scale is about 5.88
print("newImageWidth: \(newImage.size.width)") // output: 128


Which is exactly what I want, but the code scale =1/scale doesn't make any sense

What is going on here?

Answer

The init method you are trying to use is not for the purpose of resizing an image. And the scale parameter is not a resizing scale. It's the 1x, 2x, 3x scale. Essentially, the only valid values for scale are currently 1.0, 2.0, or 3.0.

While setting the scale to the inverse of what you expected gives you a size property returning your desired result, it is not at all what you should be doing.

There are proper ways to resize an image such as How to Resize image in Swift? as well as others.

Comments