之前网上有个段子说:日本女人靠化妆,韩国女人靠整容,中国女人靠美颜
足以证明相机美颜功能在中国地位是多么高,关于美颜相机的 App 在中国是那么的火
其实美颜相机的实现原理很简单,就是给采集到的图像通过添加滤镜进行渲染
核心代码
创建相机
/**sessionPreset:swift 3.0 AVCaptureSessionPreset640x480swift 4.0 AVCaptureSession.Preset.vga640x480.rawValue全屏 AVCaptureSession.Preset.hd1280x720cameraPosition:设置为前置摄像头
*/
let stillCamera: GPUImageStillCamera = GPUImageStillCamera(sessionPreset: AVCaptureSession.Preset.vga640x480.rawValue, cameraPosition: .front)
// 设置为竖屏
stillCamera.outputImageOrientation = .portrait
创建预览视图
let showView = GPUImageView(frame: UIScreen.main.bounds)
view.insertSubview(showView, at: 0)
创建滤镜组
// 初始化滤镜组
let filterGroup = GPUImageFilterGroup()// 初始化滤镜
fileprivate let exposureFilter = GPUImageExposureFilter() // 曝光
fileprivate let bilateralFilter = GPUImageBilateralFilter() // 磨皮
fileprivate let brightnessFilter = GPUImageBrightnessFilter() // 美白
fileprivate let satureationFilter = GPUImageSaturationFilter() // 饱和// 关联滤镜
bilateralFilter.addTarget(brightnessFilter)
brightnessFilter.addTarget(exposureFilter)
exposureFilter.addTarget(satureationFilter)// 设置滤镜组起点和终点 filter
filterGroup.initialFilters = [bilateralFilter]
filterGroup.terminalFilter = satureationFilter
将滤镜组、预览视图、相机相关联
// 将滤镜组、预览视图、相机相关联
stillCamera?.addTarget(filterGroup)
filterGroup?.addTarget(showView)
启动相机
stillCamera?.startCapture()
旋转摄像头
func rotateCameraAction() {stillCamera?.rotateCamera()
}
通过调整四个子滤镜的值,获取最佳美颜效果
// 修改磨皮值
// A normalization factor for the distance between central color and sample color, with a default of 8.0.
// 默认值 8.0
bilateralFilter.distanceNormalizationFactor = CGFloat(sender.value) * 8
// texelSpacingMultiplier: A multiplier for the spacing between texel reads, ranging from 0.0 on up, with a default of 4.0
// 默认值 4.0
bilateralFilter.texelSpacingMultiplier = 4.0// 修改曝光度
// Exposure ranges from -10.0 to 10.0, with 0.0 as the normal level
// [-10.0, 10.0], 0为默认值
exposureFilter.exposure = CGFloat(sender.value) * 20 - 10// 修改亮度
// Brightness ranges from -1.0 to 1.0, with 0.0 as the normal level
// [-1.0, 1.0], 0为默认值
brightnessFilter.brightness = CGFloat(sender.value) * 2 - 1// 修改饱和度
// Saturation ranges from 0.0 (fully desaturated) to 2.0 (max saturation), with 1.0 as the normal level
// [0.0, 2.0], 1.0为默认值
satureationFilter.saturation = CGFloat(sender.value) * 2
拍摄图片
func captureAction() {// 拍摄图片stillCamera?.capturePhotoAsImageProcessedUp(toFilter: filterGroup, withCompletionHandler: { (image, error) inif let image = image {// 将图片存入相册UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)}})
}