iosswiftuiimagepngrepresentationcgimagesource

App Crash When I use CGImageSourceCreateThumbnailAtIndex in Swift


I just use CGImageSourceCreateThumbnailAtIndex to scale down UIImage size . I get crash Message :

"IIONumber -- 'num' is not a CFNumberRef" .

I could not find what is it? Thanks

func scaleDownImage()->void{   

   var nextImage = UIImage()
    if let img = nextDicData["img"] as? UIImage{
        let data = UIImagePNGRepresentation(img)
        if let cgimageSource = CGImageSourceCreateWithData(data! as CFData, nil){
            let option : [NSString : Any] = [kCGImageSourceThumbnailMaxPixelSize : self.outputSize, kCGImageSourceCreateThumbnailFromImageAlways : true]
            // That's crash at bellow line      
            if let scaleImage = CGImageSourceCreateThumbnailAtIndex(cgimageSource, 0, option as CFDictionary){
                nextImage = UIImage(cgImage: scaleImage)
            }
        }
    }
}

Solution

  • The dictionary option passed to CGImageSourceCreateThumbnailAtIndex method contains kCGImageSourceThumbnailMaxPixelSize. It should be CFNumber.

    Apple's documentation on kCGImageSourceThumbnailMaxPixelSize

    The maximum width and height in pixels of a thumbnail. If this key is not specified, the width and height of a thumbnail is not limited and thumbnails may be as big as the image itself. If present, this key must be a CFNumber value.

    Please ensure it is CFNumber. I believe thats the reason for the crash. Please find the Apple's reference here: https://developer.apple.com/documentation/imageio/kcgimagesourcethumbnailmaxpixelsize?language=objc

    Try options like this.

    let options = [
        kCGImageSourceCreateThumbnailWithTransform: true,
        kCGImageSourceCreateThumbnailFromImageAlways: true,
        kCGImageSourceThumbnailMaxPixelSize: 250 /* some size */] as CFDictionary