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?