当我在 Swift 中使用 CGImageSourceCreateThumbnailAtIndex 时应用程序崩溃

App Crash When I use CGImageSourceCreateThumbnailAtIndex in Swift

我只是使用 CGImageSourceCreateThumbnailAtIndex 缩小 UIImage 大小。我收到崩溃消息:

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

我找不到它是什么? 谢谢

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)
            }
        }
    }
}

传递给 CGImageSourceCreateThumbnailAtIndex 方法的字典选项包含 kCGImageSourceThumbnailMaxPixelSize。应该是CFNumber.

Apple 关于 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.

请确保是CFNumber。我相信这就是崩溃的原因。请在此处找到 Apple 的参考资料:https://developer.apple.com/documentation/imageio/kcgimagesourcethumbnailmaxpixelsize?language=objc

试试这样的选项。

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