import Foundation
import UIKit
extension UIImage {
/* 压缩图片 */
func imageCompress(toScale: CGFloat) -> UIImage {
let targetHeight = toScale * self.size.height
let targetWidth = toScale * self.size.width
let size = CGSize(width: targetWidth, height: targetHeight)
//创建一个基于位图的上下文
UIGraphicsBeginImageContext(size)
self.draw(in: CGRect(x: 0, y: 0, width: targetWidth, height: targetHeight))
//根据size 返回图形大小
let newImg : UIImage = UIGraphicsGetImageFromCurrentImageContext()!
//关闭上下文
UIGraphicsEndImageContext()
return newImg
}
/* 图片模糊 */
func blurImage(value:NSNumber) -> UIImage {
// CoreImage
let context = CIContext(options: [kCIContextUseSoftwareRenderer: true])
//根据UIImage 创建 CIImage类型,进行操作,然后再返回 UIImage类型
let ciImg = CIImage(image: self)
//滤镜
let blurFilter = CIFilter(name: "CIGaussianBlur")
blurFilter?.setValue(ciImg, forKey: kCIInputImageKey)
//设置模糊程度
blurFilter?.setValue(value, forKey: "inputRadius")
let imageRef = context.createCGImage((blurFilter?.outputImage)!, from: (ciImg?.extent)!)
let newImg = UIImage(cgImage: imageRef!)
return newImg
}
/*
出现问题:因为在模糊的时候,边缘会变成半透明的状态,所以理想状况是可以对原图像进行适当放大,选择使用CIAffineClamp在模糊之前对图像进行处理。
*/
func blurImageAnother(value:NSNumber) -> UIImage {
// CoreImage
let context = CIContext(options: [kCIContextUseSoftwareRenderer: true])
//根据UIImage 创建 CIImage类型,进行操作,然后再返回 UIImage类型
let inputImage = CIImage(image: self)
//滤镜
let affineClampFilter = CIFilter(name: "CIAffineClamp")
let xform = CGAffineTransform(scaleX: 1.0, y: 1.0)
affineClampFilter?.setValue(inputImage, forKey: kCIInputImageKey)
affineClampFilter?.setValue(NSValue.init(cgAffineTransform: xform), forKey: "inputTransform")
let outinputImg = affineClampFilter?.outputImage!
let blurFilter = CIFilter(name: "CIGaussianBlur")
blurFilter?.setValue(outinputImg, forKey: kCIInputImageKey)
//设置模糊程度
blurFilter?.setValue(value, forKey: "inputRadius")
let imageRef = context.createCGImage((blurFilter?.outputImage)!, from: (inputImage?.extent)!)
let newImg = UIImage(cgImage: imageRef!)
return newImg
}
}