How to find the color of a single pixel in UIImage in fast

I have the following quick code.

let resolution = [imageView.frame.size.width, imageView.frame.size.height]

for x in 0...Int(resolution[0]) {
    for y in 0...Int(resolution[1]) {
        let coordinate = [x, y]
        //Find the colour of the pixel here
    }
}

I want to be able to find the color displayed by each individual pixel in the photo. Is there a way to change the code where I put "// Find the pixel color here" to make it print the RGB value of the pixel in the coordinate represented by the constant coordinate?

+4
source share
2 answers

You can try the following:

var pixel : [UInt8] = [0, 0, 0, 0]
var colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue)
let context = CGBitmapContextCreate(UnsafeMutablePointer(pixel), 1, 1, 8, 4, colorSpace, bitmapInfo)

Hope this helps!

+3
source

Adding @Horray to the answer to get the color values ​​you need to do two more lines. Just check this implementation,

var pixel : [UInt8] = [0, 0, 0, 0]
var colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue)
let context = CGBitmapContextCreate(UnsafeMutablePointer(pixel), 1, 1, 8, 4, colorSpace, bitmapInfo)

// Translate the context your required point(x,y)
CGContextTranslateCTM(context, -x, -y);
yourImageView.layer.renderInContext(context)

NSLog("pixel: %d %d %d %d", pixel[0], pixel[1], pixel[2], pixel[3]);

let redColor : Float = Float(pixel[0])/255.0
let greenColor : Float = Float(pixel[1])/255.0
let blueColor: Float = Float(pixel[2])/255.0
let colorAlpha: Float = Float(pixel[3])/255.0

// Create UIColor Object    
var color : UIColor! = UIColor(red: CGFloat(redColor), green: CGFloat(greenColor), blue: CGFloat(blueColor), alpha: CGFloat(colorAlpha))
+2
source

Source: https://habr.com/ru/post/1584155/


All Articles