如何在swift中找到UIImage中单个像素的颜色

时间:2015-04-23 04:37:29

标签: ios image swift uiimageview analysis

我有以下快速代码。

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
    }
}

我希望能够找到照片中每个像素显示的颜色。有没有办法修改我放置的代码“//在这里找到像素的颜色”,以便在常量坐标表示的坐标处打印像素的RGB值?

2 个答案:

答案 0 :(得分:3)

您可以尝试以下操作:

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)

希望这会有所帮助!!

答案 1 :(得分:2)

Adding to @Horray's answer, to get the color values you have to execute 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))