0

I am referring to ZImageCropper for my project to crop an image. However, it reduces the quality of the image during conversion.

I know one of the reasons the quality of image was reduced is due to UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, 1)

I have tried changing it to UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, 0) and UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, UIScreen.main.scale)

I reference my code from Resize and Crop 2 Images affected the original image quality It does help but when I check the quality of the image, it is still reduced. Is there any way to prevent a reduction in image quality?

Roy Scheffers
  • 3,832
  • 11
  • 31
  • 36
KUROYUKI
  • 113
  • 4
  • 16
  • You cropped an image, stretched it back out to the same size as the original, and you're disappointed that the quality decreased? What did you expect to happen? (I didn't downvote, btw) – Alexander Aug 29 '18 at 06:03
  • Hi @Alexander thanks for not down voting, I am sorry but I am a bit confuse. what so you mean by stretching the image? the image is actually no blurry but the but when I counted the pixel in the image it's 1/3 of what it should be – KUROYUKI Aug 29 '18 at 06:18

1 Answers1

3

in iOS 10 and above you can resize any UIImage without quality loss, hope this helps:

func resize(targetSize: CGSize) -> UIImage {
    if #available(iOS 10.0, *) {
        return UIGraphicsImageRenderer(size: targetSize).image { _ in
            self.draw(in: CGRect(origin: .zero, size: targetSize))
        }
    } else {
        return resizeImage(maxSize: targetSize.width)
    }
}


func resizeImage(maxSize: CGFloat) -> UIImage {
    var newWidth = size.width
    var newHeight = size.height

    if size.width >= maxSize {
        newWidth = min(maxSize, size.width)
        newHeight = maxSize * size.height / size.width
    } else if size.height >= maxSize {
        newHeight = min(maxSize, size.height)
        newWidth = maxSize * size.width / size.height
    }

    UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
    draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage!
}
Ali Moazenzadeh
  • 584
  • 4
  • 13