Skip to content

Instantly share code, notes, and snippets.

@benguild
Last active February 8, 2019 04:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benguild/bdfe6b4cd6d247015e7e3305a8d4cfc2 to your computer and use it in GitHub Desktop.
Save benguild/bdfe6b4cd6d247015e7e3305a8d4cfc2 to your computer and use it in GitHub Desktop.
private func cameraPreviewObfuscationImage(from image: CIImage, with blurRadius: CGFloat, at targetSize: CGSize) -> UIImage? {
var blurAdjustedTargetSize = targetSize
if targetSize.width > targetSize.height {
blurAdjustedTargetSize.height += blurRadius * 2
} else {
blurAdjustedTargetSize.width += blurRadius * 2
}
let croppedImage = image.cropped(to: AVMakeRect(aspectRatio: blurAdjustedTargetSize, insideRect: image.extent))
let targetScaledSize = targetSize.aspectFill(within: blurAdjustedTargetSize)
let resizedImage = croppedImage.applyingFilter(
"CILanczosScaleTransform",
parameters: [
kCIInputScaleKey: max(
targetScaledSize.width / croppedImage.extent.width,
targetScaledSize.height / croppedImage.extent.height
),
kCIInputAspectRatioKey: 1
]
)
let blurredImage = resizedImage
.clampedToExtent()
.applyingFilter(
"CIGaussianBlur",
parameters: [
kCIInputRadiusKey: blurRadius
]
)
.cropped(to: resizedImage.extent)
guard let outputImage = coreImageContext.createCGImage(blurredImage, from: blurredImage.extent) else { return nil }
return UIImage(cgImage: outputImage)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment