Swift - 给图片添加滤镜效果(棕褐色老照片滤镜,黑白滤镜)

Core Image是一个强大的滤镜处理框架。它除了可以直接给图片添加各种内置滤镜,还能精确地修改鲜艳程度, 色泽, 曝光等,下面通过两个样例演示如何给UIImage添加滤镜。

1,棕褐色滤镜  - CISepiaTone
这个有点复古老照片发黄的效果(上面一张是原图)。
原文:Swift - 给图片添加滤镜效果(棕褐色老照片滤镜,黑白滤镜)

扩展UIImage类,添加棕褐色滤镜:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import UIKit
 
//--- UIImageFilterExtension.swift ---
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
原文:Swift - 给图片添加滤镜效果(棕褐色老照片滤镜,黑白滤镜)

 
扩展UIImage类,添加黑白滤镜:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import UIKit
 
//--- UIImageFilterExtension.swift ---
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()

原文出自:www.hangge.com  转载请保留原文链接:http://www.hangge.com/blog/cache/detail_889.html
posted @ 2015-10-07 11:04  brave-sailor  阅读(806)  评论(0编辑  收藏  举报