我试图在函数CGImageSourceCreateThumbnailAtIndex的帮助下从现有CGImage生成缩略图。
在我发现的所有示例中,所提供的图像源都是在图像网址的帮助下创建的。
由于我没有任何网址 - 只有图片数据 - 我试过这样:
func createThumbnailForImage(image: CGImage, size: Int) -> CGImage?
{
var provider = CGImageGetDataProvider(image)
if let imageSource = CGImageSourceCreateWithDataProvider(provider, nil)
{
let swiftDict = [
kCGImageSourceThumbnailMaxPixelSize as String : size,
kCGImageSourceCreateThumbnailFromImageIfAbsent as String : true
]
let nsDict = swiftDict as NSDictionary
let cfDict = nsDict as CFDictionary
return CGImageSourceCreateThumbnailAtIndex(imageSource, 0, cfDict)
}
return nil
}
我得到的结果总是零。
我的猜测是图像来源出了问题,但无法确定问题。
答案 0 :(得分:0)
Swift 3有实现缩略图生成
import Foundation
import UIKit
import ImageIO
class PhotoUtils: NSObject {
static func thumbnail(url:CFURL) -> UIImage {
let src = CGImageSourceCreateWithURL(url, nil)
return thumbnailImage(src: src!)
}
static func thumbnail(data imageData:CFData) -> UIImage {
let src = CGImageSourceCreateWithData(imageData, nil)
return thumbnailImage(src: src!)
}
static private func thumbnailImage(src: CGImageSource) -> UIImage {
let scale = UIScreen.main.scale
let w = (UIScreen.main.bounds.width / 3) * scale
let d : [NSObject:AnyObject] = [
kCGImageSourceShouldAllowFloat : true as AnyObject,
kCGImageSourceCreateThumbnailWithTransform : true as AnyObject,
kCGImageSourceCreateThumbnailFromImageAlways : true as AnyObject,
kCGImageSourceThumbnailMaxPixelSize : w as AnyObject
]
let imref = CGImageSourceCreateThumbnailAtIndex(src, 0, d as CFDictionary)
return UIImage(cgImage: imref!, scale: scale, orientation: .up)
}
}