Skip to content

Instantly share code, notes, and snippets.

@marchinram
Last active January 19, 2022 08:53
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save marchinram/3675efc96bf1cc2c02a5 to your computer and use it in GitHub Desktop.
Save marchinram/3675efc96bf1cc2c02a5 to your computer and use it in GitHub Desktop.
iOS Swift UIImage subscript extension to get pixel color
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)
}
}
@herbgarlow
Copy link

Could you possibly provide an example of how to "call" this example to obtain the RGBA values? Please and thankyou. :-)

@marchinram
Copy link
Author

@herbgarlow sure, something like this:

let image = UIImage(named: "someimage")!
if let color = image[100, 100] {
    var red: CGFloat = 0.0
    var green: CGFloat = 0.0
    var blue: CGFloat = 0.0
    var alpha: CGFloat = 0.0
    color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)

    // Do something with the color
}

Remember the subscript returns an optional incase you gave an out of bounds x or y value

@zimingw25
Copy link

can this code show the color of the pixel of a image? For example, I have uiImage, and I would like to know the color of the pixel located in [100.100], how to operate?

@pronebird
Copy link

This code won't work if image is stored in BGR format.

@eaigner
Copy link

eaigner commented Jan 16, 2018

Why are you copying your data? You can get the byte pointer directly from the provider.

@theLeroy
Copy link

theLeroy commented Jul 3, 2019

image

Ive got these errors. whats wrong?

@marchinram
Copy link
Author

marchinram commented Jul 3, 2019 via email

@aditiswaroop
Copy link

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.

@Shiko007
Copy link

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