Swift - 给图片添加滤镜效果(棕褐色老照片滤镜,黑白滤镜)
转载
Core Image是一个强大的滤镜处理框架。它除了可以直接给图片添加各种内置滤镜,还能精确地修改鲜艳程度, 色泽, 曝光等,下面通过两个样例演示如何给UIImage添加滤镜。
1,棕褐色滤镜 - CISepiaTone
这个有点复古老照片发黄的效果(上面一张是原图)。
扩展UIImage类,添加棕褐色滤镜:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
import UIKit
extension UIImage
{
func sepiaTone() -> UIImage ?
{
let imageData = UIImagePNGRepresentation ( self )
let inputImage = CoreImage . CIImage (data: imageData!)
let context = CIContext (options: nil )
let filter = CIFilter (name: "CISepiaTone" )
filter !.setValue(inputImage, forKey: kCIInputImageKey)
filter !.setValue(0.8, forKey: "inputIntensity" )
if let outputImage = filter !.outputImage {
let outImage = context.createCGImage(outputImage, fromRect: outputImage.extent)
return UIImage ( CGImage : outImage)
}
return nil
}
}
|
使用样例:
1
|
imageView1.image = UIImage (named: "img2.jpg" )?.sepiaTone()
|
2,黑白滤镜 - CIPhotoEffectNoir
扩展UIImage类,添加黑白滤镜:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
import UIKit
extension UIImage
{
func noir() -> UIImage ?
{
let imageData = UIImagePNGRepresentation ( self )
let inputImage = CoreImage . CIImage (data: imageData!)
let context = CIContext (options: nil )
let filter = CIFilter (name: "CIPhotoEffectNoir" )
filter !.setValue(inputImage, forKey: kCIInputImageKey)
if let outputImage = filter !.outputImage {
let outImage = context.createCGImage(outputImage, fromRect: outputImage.extent)
return UIImage ( CGImage : outImage)
}
return nil
}
}
|
使用样例:
1
|
imageView1.image = UIImage (named: "img2.jpg" )?.noir()
|
本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。