c语⾔缩略图算法,获取图像缩略图的框架
⼀、UIKit
extension UIImage {
//UIKit
func resizeUI(size: CGSize) -> UIImage? {
let hasAlpha = false
let scale: CGFloat = 0.0 // Automatically use scale factor of main screen
/**
创建⼀个图⽚类型的上下⽂。调⽤UIGraphicsBeginImageContextWithOptions函数就可获得⽤来处理图⽚的图形上下⽂。利⽤该上下⽂,你就可以在其上进⾏绘图,并⽣成图⽚
size:表⽰所要创建的图⽚的尺⼨
opaque:表⽰这个图层是否完全透明,如果图形完全不⽤透明最好设置为YES以优化位图的存储,这样可以让图层在渲染的时候效率更⾼
scale:指定⽣成图⽚的缩放因⼦,这个缩放因⼦与UIImage的scale属性所指的含义是⼀致的。传⼊0则表⽰让图⽚的缩放因⼦根据屏幕的分辨率⽽变化,所以我们得到的图⽚不管是在单分辨率还是视⽹膜屏上看起来都会很好
*/
UIGraphicsBeginImageContextWithOptions(size, !hasAlpha, scale)
self.draw(in: CGRect(origin: .zero, size: size))
let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return resizedImage!
}
}
⼆、CoreGraphics
extension UIImage {
//CoreGraphics
func resizeCG(size:CGSize) -> UIImage? {
guard let cgImage = Image else { return nil }
let bitsPerComponent = cgImage.bitsPerComponent
let bytesPerRow = cgImage.bytesPerRow
let colorSpace = lorSpace
let bitmapInfo = cgImage.bitmapInfo
guard let context = CGContext(data: nil,
width: Int(size.width),resized
height: Int(size.height),
bitsPerComponent: bitsPerComponent,
bytesPerRow: bytesPerRow,
space: colorSpace!,
bitmapInfo: bitmapInfo.rawValue) else {
return nil
}
context.interpolationQuality = .high
context.draw(cgImage, in: CGRect(origin: .zero, size: size))
let resizedImage = context.makeImage().flatMap {
UIImage(cgImage: $0)
}
return resizedImage
}
}
三、ImageIO
extension UIImage {
//ImageIO
func resizeIO(size:CGSize) -> UIImage? {
guard let data = UIImagePNGRepresentation(self) else { return nil }
let maxPixelSize = max(size.width, size.height)
/
/let imageSource = CGImageSourceCreateWithURL(url, nil)
guard let imageSource = CGImageSourceCreateWithData(data as CFData, nil) else { return nil }
//kCGImageSourceThumbnailMaxPixelSize为⽣成缩略图的⼤⼩。当设置为800,如果图⽚本⾝⼤于800*600,则⽣成后图⽚⼤⼩为800*600,如果源图⽚为700*500,则⽣成图⽚为800*500
let options: [NSString: Any] = [
kCGImageSourceThumbnailMaxPixelSize: maxPixelSize,
kCGImageSourceCreateThumbnailFromImageAlways: true
]
let resizedImage = CGImageSourceCreateImageAtIndex(imageSource, 0, options as CFDictionary).flatMap{
UIImage(cgImage: $0)
}
return resizedImage
}
}
四、CoreImage
extension UIImage {
//CoreImage
func resizeCI(size:CGSize) -> UIImage? {
guard let cgImage = Image else { return nil }
let scale = (Double)(size.width) / (Double)(self.size.width)
let image = CIImage(cgImage: cgImage)
let filter = CIFilter(name: "CILanczosScaleTransform")!
filter.setValue(image, forKey: kCIInputImageKey)
filter.setValue(NSNumber(value:scale), forKey: kCIInputScaleKey)
filter.setValue(1.0, forKey:kCIInputAspectRatioKey)
guard let outputImage = filter.value(forKey: kCIOutputImageKey) as? CIImage else { return nil} let context = CIContext(options: [kCIContextUseSoftwareRenderer: false])
let resizedImage = ateCGImage(outputImage, from: ).flatMap { UIImage(cgImage: $0)
}
return resizedImage
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论