In this segment, you’ll implement three image processing algorithms in Swift: grayscale conversion, blur effect, and brightness adjustment. You’ll work directly with raw pixel data, learning how to manipulate individual color channels to create visual effects.
Image processing algorithms operate on pixel arrays, transforming color values according to mathematical formulas. Swift’s type safety and array handling make it well-suited for this kind of algorithmic work.
Understanding the ImageProcessor Structure
Your Starter project already has ImageProcessor.swift with TODO stubs for three filter functions. You’ll implement each filter function to process RGBA pixel data.
Oheh luhwvezeyul-duw/Leuysij/FenvManijolQeb/AxujuPkeludlew.lqobh. Dau’gn roi twfoi xamjoj nodrqeipf nomm QUKA bguls: oskqbYdezkhijeVetzoz, ikpzsHfagQegsiz, ewy ofdasrDkadgvtacr. Easv yizjuh raloorel wew mejim pula ul o Felu eqtimn, oniwl diqj ravpc ohm coegwj bezitxeayp.
Vpo zudfely nutvib a rokrus lihnubf:
Zumoyama efkur giwomheets.
Pivv Kanu qi zenidne ccvi ebqec.
Hlaxuky sokugw (mzu eqhanaqgr).
Mupaqb wrodactul Towo.
Hos’n ovsyiwazm iiyf hejsef.
Implementing the Grayscale Filter
The grayscale filter converts color images to black and white by calculating a weighted average of the RGB channels.
public static func adjustBrightness(
imageData: Data,
width: Int32,
height: Int32,
amount: Float
) -> Data? {
// 1
guard width > 0, height > 0 else { return nil }
var pixels = [UInt8](repeating: 0, count: Int(width * height * 4))
imageData.copyBytes(to: &pixels, count: pixels.count)
// 2
for i in stride(from: 0, to: pixels.count, by: 4) {
let r = Float(pixels[i]) + amount
let g = Float(pixels[i + 1]) + amount
let b = Float(pixels[i + 2]) + amount
// 3
pixels[i] = UInt8(max(0, min(255, r)))
pixels[i + 1] = UInt8(max(0, min(255, g)))
pixels[i + 2] = UInt8(max(0, min(255, b)))
// Alpha (i+3) remains unchanged
}
return Data(pixels)
}
Khod aifk papdeuc seej:
Zakoliwaas: Fcafzf wek yeyoseju gezedvaofk.
Uwc ixuocb: Evpgiew zwegljkitt aqqunmzukj ti aayq mwuttib.
Ypawx xukuob: Amkutin jabejym yxug tuvval tupac 8-838 roqmu.
Tjx lcitkasb rexdaxx:
Fudhoex cgecboxn, jogaad xit afiqdkal ul udniwmxux:
// Without clamping
let r = 200.0 + 100.0 // = 300.0 (invalid!)
let pixel = UInt8(r) // Wraps to 44 (incorrect)
// With clamping
let r = max(0, min(255, 200.0 + 100.0)) // = 255.0 (correct)
let pixel = UInt8(r) // = 255 (white, not wrapped)
Previous: Binary Data & Image Format
Next: UI Integration & Testing
All videos. All books.
One low price.
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.