Apply a Filter to an Image in SwiftUI
Written by Team Kodeco
Sometimes, we need to apply filters to images to enhance their appearance or improve their quality. SwiftUI can use Core Image built-in filters to manipulate images with ease.
Here’s an example of applying a filter to an image in SwiftUI:
import SwiftUI
import CoreImage
import CoreImage.CIFilterBuiltins
struct ContentView: View {
let image: Image
init() {
let uiImage = UIImage(named: "CoolCat") ?? UIImage()
let filteredUIImage = ContentView.applySepiaFilter(to: uiImage)
image = Image(uiImage: filteredUIImage)
}
var body: some View {
image
.resizable()
.scaledToFit()
}
static func applySepiaFilter(to inputImage: UIImage) -> UIImage {
guard let ciImage = CIImage(image: inputImage) else { return inputImage }
let filter = CIFilter.sepiaTone()
filter.inputImage = ciImage
filter.intensity = 1.0
// Get a CIContext
let context = CIContext()
// Create a CGImage from the CIImage
guard let outputCIImage = filter.outputImage,
let cgImage = context.createCGImage(outputCIImage, from: outputCIImage.extent) else {
return inputImage
}
// Create a UIImage from the CGImage
let outputUIImage = UIImage(cgImage: cgImage)
return outputUIImage
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
The preview should look as follows:
Here’s how this code works, beginning with the init
method:
-
Loads a
UIImage
from the app bundle with the name “CoolCat”. If this fails, it initializes an emptyUIImage
. -
Calls a static function
applySepiaFilter(to:)
that applies a sepia filter to the loaded image. The result is then wrapped in a SwiftUIImage
and stored inimage
. -
Next, you create a static function
applySepiaFilter(to:)
that:- Takes a
UIImage
as input. - Converts it into a
CIImage
(a representation of an image for processing with Core Image). - Applies a sepia filter to the image by using
CIFilter.sepiaTone()
. The intensity of the filter effect is set to the maximum (1.0). - Converts the
CIImage
back to aCGImage
and then to aUIImage
. - If any of these conversions fail, the original, unfiltered image is returned.
- Takes a
In summary, this SwiftUI view will display an image named CoolCat from the app’s resources with a sepia tone filter applied. If the image doesn’t exist or the filter can’t be applied for some reason, it will display an empty image.
Core Image Filter Choices
Here are some other Core Image filters to try:
-
gaussianBlur
applies a Gaussian blur to an image. This is often used for creating depth-of-field effects or blur effects for focus emphasis. -
colorInvert
inverts all the colors in an image. It’s useful when you want to create a negative of the existing image. -
photoEffectMono
applies a monochrome effect to the image, similar to black-and-white photography. This might be used to add an old-school or vintage effect to photos. -
pixellate
applies a pixelation effect, making the image appear as though it’s composed of large pixels. This might be used to create a retro video game aesthetic or to obscure details for privacy. -
sharpenLuminance
sharpens the image by increasing the contrast of the adjacent pixels. This can be used to make a photo clearer or to enhance the details. -
vignette
darkens the corners of the image to draw attention to the center. It’s a popular effect for portrait and landscape photography. -
sepiaTone
You’ve already tried this one, but for completeness: this filter applies a sepia tone to the image, which gives the image an aged or vintage look. -
photoEffectInstant
applies a Polaroid effect to the image. It could be used to mimic the look of instant films. -
colorMonochrome
turns your image into monochrome with a tint of a specified color. This can be used for various aesthetic purposes, to focus on a single color range, or to create a mood that corresponds to a specific color. -
unsharpMask
increases the contrast of the edges between pixels with different color values while keeping noise to a minimum. It can be used to make an image look more defined or “sharper”. -
bloom
applies a glow effect that causes bright areas to appear to bleed outwards. This can be used for various aesthetic effects, such as to create a dreamy look.
For instance, to create a Gaussian blur filter, you would use the CIFilter.gaussianBlur()
method. Similarly, for color inversion, you’d use CIFilter.colorInvert()
, and so on.
You can use any of the built-in filters to manipulate the image appearance and create stunning effects. With the addition of filters, we can now enhance the visual appeal of our app’s user interface.