Last active
January 19, 2022 08:53
-
-
Save marchinram/3675efc96bf1cc2c02a5 to your computer and use it in GitHub Desktop.
iOS Swift UIImage subscript extension to get pixel color
This file contains 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
import UIKit | |
extension UIImage { | |
subscript (x: Int, y: Int) -> UIColor? { | |
guard x >= 0 && x < Int(size.width) && y >= 0 && y < Int(size.height), | |
let cgImage = cgImage, | |
let provider = cgImage.dataProvider, | |
let providerData = provider.data, | |
let data = CFDataGetBytePtr(providerData) else { | |
return nil | |
} | |
let numberOfComponents = 4 | |
let pixelData = ((Int(size.width) * y) + x) * numberOfComponents | |
let r = CGFloat(data[pixelData]) / 255.0 | |
let g = CGFloat(data[pixelData + 1]) / 255.0 | |
let b = CGFloat(data[pixelData + 2]) / 255.0 | |
let a = CGFloat(data[pixelData + 3]) / 255.0 | |
return UIColor(red: r, green: g, blue: b, alpha: a) | |
} | |
} |
I haven’t looked at this code in awhile but looks like it needs a guard statement, I can update a lil later today
…Sent from my iPhone
On Jul 3, 2019, at 08:10, Leroy ***@***.***> wrote:
Ive got these errors. whats wrong?
—
You are receiving this because you authored the thread.
Reply to this email directly, view it on GitHub, or mute the thread.
I want to extract RGB values for all pixels from a frame captured during ARSession. The CVPixelBufferFormat for that is of type kCVPixelFormatType_420YpCbCr8BiPlanarFullRange. Will this code work for this format type as well?
I am new to Swift, I am having a tough time trying to understand the format types and difference in manipulating them.
Doesn't work on black for some reason
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ive got these errors. whats wrong?