Last active
June 5, 2021 03:47
-
-
Save skounis/85c7758bbe6e2a622fb2 to your computer and use it in GitHub Desktop.
Image manipulation example in Swift demonstrating UIImage, RGBAImage,
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: Playground - noun: a place where people can play | |
import UIKit | |
var str = "Hello, playground" | |
let image = UIImage(named: "demo.jpg")! | |
let myRGBA = RGBAImage(image: image)! | |
// | |
// Change the RGB values of a particular pixel | |
// | |
// Pixel location | |
let x = 10 | |
let y = 10 | |
// Pixel index | |
let index = y * myRGBA.width + x | |
// Pixel itself | |
var pixel = myRGBA.pixels[index] | |
pixel.red | |
pixel.green | |
pixel.blue | |
pixel.red = 255 | |
pixel.green = 0 | |
pixel.blue = 0 | |
myRGBA.pixels[index] = pixel | |
let newImage = myRGBA.toUIImage() | |
// | |
// Calculate the avarage RGB values of the image | |
// | |
/* | |
// RGB accumulator | |
var totalRed = 0 | |
var totalGreen = 0 | |
var totalBlue = 0 | |
for y in 0..<myRGBA.height { | |
for x in 0..<myRGBA.width{ | |
// Pixel index | |
let index = y * myRGBA.width + x | |
var pixel = myRGBA.pixels[index] | |
totalRed += Int(pixel.red) | |
totalGreen += Int(pixel.green) | |
totalBlue += Int(pixel.blue) | |
} | |
} | |
let count = myRGBA.width * myRGBA.height | |
let avgRed = totalRed / count | |
let avgGreen = totalGreen / count | |
let avgBlue = totalBlue / count | |
*/ | |
// | |
// Amplify the red color | |
// | |
// Calculated RGB accumulator | |
let avgRed = 136 | |
let avgGreen = 131 | |
let avgBlue = 134 | |
for y in 0..<myRGBA.height { | |
for x in 0..<myRGBA.width{ | |
// Pixel index | |
let index = y * myRGBA.width + x | |
var pixel = myRGBA.pixels[index] | |
let redDiff = Int(pixel.red) - avgRed | |
if redDiff > 0 { | |
pixel.red = UInt8(max(0, min(255, avgRed + redDiff * 5))) | |
myRGBA.pixels[index] = pixel | |
} | |
} | |
} | |
let newImage2 = myRGBA.toUIImage() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment