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?
func getScaledDimension(width: CGFloat, height: CGFloat,new_width: CGFloat, new_height: CGFloat)->CGPoint {
let widthAspect = (width / new_width)
let heightAspect = (height / new_height)
if widthAspect == 0 || heightAspect == 0 {
return CGPoint(x: width, y: height)
}
var width1 : CGFloat = 0
var height1 : CGFloat = 0
if widthAspect > heightAspect {
width1 = (width) / heightAspect
height1 = (height) / heightAspect
} else {
width1 = (width) / widthAspect
height1 = (height) / widthAspect
}
return CGPoint(x: width1, y: height1 )
}
func ResizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
let rect = CGRectMake(0, 0, targetSize.width, targetSize.height)
UIGraphicsBeginImageContextWithOptions(targetSize, false, 1.0)
image.drawInRect(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
let imagesize = getScaledDimension(image.size.width, height: image.size.height , new_width: Width, new_height: Hieght)
print("Image Size Scaled Dimension -> H:\(imagesize.x) W:\(imagesize.y)")
let newImage = ResizeImage(image, targetSize: CGSizeMake(imagesize.x,imagesize.y))
print("Resize Image Size -> H\(newImage.size.height) W\(newImage.size.width) ")