I got a large image with 1920x1080 pixels. I'm trying to scale Image with 2 differents ways:

First: using CIFilter

    func resize(image: UIImage, scale: Float, aspect: Float = 1) -> UIImage? {
    return autoreleasepool(invoking: {
        [weak self] () -> UIImage? in

        var filter: CIFilter! = CIFilter(name: "CILanczosScaleTransform")!
        filter.setValue(CIImage(image: image), forKey: kCIInputImageKey)
        filter.setValue(NSNumber(value: scale as Float), forKey: kCIInputScaleKey)
        filter.setValue(NSNumber(value: aspect as Float), forKey: kCIInputAspectRatioKey)

        var result: UIImage?
        var cgImage: CGImage? = nil
        if let outputImage = filter.outputImage {
            cgImage = self?.ctx?.createCGImage(outputImage, from: outputImage.extent)
        }
        if let cgImg = cgImage {
            result = self?.convertUIImage(fromCGImage: cgImg)
        }
        if #available(iOS 10.0, *) {
            self?.ctx?.clearCaches()
        }
        cgImage = nil
        filter.setValue(nil, forKey: kCIInputImageKey)
        filter.setValue(nil, forKey: kCIInputScaleKey)
        filter.setValue(nil, forKey: kCIInputAspectRatioKey)
        filter.setDefaults()
        filter = nil
        return result
    })
}

Second: using UIImage()

func scaleImage(scale: CGFloat) -> UIImage? {
        if let cgImage = self.cgImage {
            return UIImage(cgImage: cgImage, scale: scale, orientation: imageOrientation)
        }
        return nil
    }

But I realized that the scale factor in two methods produced conflicting results. For example, I set scale equal to 2 But in first method: new image is size (3840x2160), and second is (960x540).

I'm really confused. Can anyone explain me why this happened In the future when using a new function have parameter scale how do I know when scale make my image smaller and vice versa

1 Answers

0
Ruben Nahatakyan On

By default image has scale, its can any value. In began your image scale can be bigger than 2, that why your second way your image received smaller. Try this.

func scaleImage(image: UIImage, scale: CGFloat) -> UIImage? {
    let size = CGSize(width: image.size.width * scale, height: image.size.height * scale)
    let drawRect = CGRect(origin: .zero, size: size)

    UIGraphicsBeginImageContextWithOptions(size, false, 0)

    image.draw(in: drawRect)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()

    return newImage
}