我尝试了不同的解决方案(例如this one),但我得到的颜色看起来与实际图像略有不同。我想这是因为图片只有Set sh = CreateObject("WScript.Shell")
sh.CurrentDirectory = "C:\some\folder"
,而不是RGB
。这可能是一个问题吗?
相关问题:如果UIImage有RGBA
,我是否必须重新计算图片,或者我可以使用contentMode = .scaleAspectFill
吗?
编辑:
我尝试使用此扩展程序:
imageView.image
但是对于某些图像来说,好像坐标系已经转过来了,对于其他人来说,我得到了错误的价值......我在这里错过了什么?
编辑2:
我尝试使用这些图片:
https://dl.dropboxusercontent.com/u/119600/gradient.png https://dl.dropboxusercontent.com/u/119600/gradient@2x.png
但我确实得到了错误的价值观。它们嵌入extension CALayer {
func getPixelColor(point: CGPoint) -> CGColor {
var pixel: [CUnsignedChar] = [0, 0, 0, 0]
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
let context = CGContext(data: &pixel, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)
context!.translateBy(x: -point.x, y: -point.y)
self.render(in: context!)
let red: CGFloat = CGFloat(pixel[0]) / 255.0
let green: CGFloat = CGFloat(pixel[1]) / 255.0
let blue: CGFloat = CGFloat(pixel[2]) / 255.0
let alpha: CGFloat = CGFloat(pixel[3]) / 255.0
let color = UIColor(red:red, green: green, blue:blue, alpha:alpha)
return color.cgColor
}
}
但我转换坐标:
UIImageView
这一个
在iPhone 7模拟器上运行时给我private func convertScreenPointToImage(point: CGPoint) -> CGPoint {
let widthMultiplier = gradientImage.size.width / UIScreen.main.bounds.width
let heightMultiplier = gradientImage.size.height / UIScreen.main.bounds.height
return CGPoint(x: point.x * widthMultiplier, y: point.y * heightMultiplier)
}
,这是不正确的......
答案 0 :(得分:3)
func pixel(in image: UIImage, at point: CGPoint) -> (UInt8, UInt8, UInt8, UInt8)? {
let width = Int(image.size.width)
let height = Int(image.size.height)
let x = Int(point.x)
let y = Int(point.y)
guard x < width && y < height else {
return nil
}
guard let cfData:CFData = image.cgImage?.dataProvider?.data, let pointer = CFDataGetBytePtr(cfData) else {
return nil
}
let bytesPerPixel = 4
let offset = (x + y * width) * bytesPerPixel
return (pointer[offset], pointer[offset + 1], pointer[offset + 2], pointer[offset + 3])
}
let image = UIImage(named: "t.png")!
if let (r,g,b,a) = pixel(in: image, at: CGPoint(x: 1, y:2)) {
print ("Red: \(r), Green: \(g), Blue: \(b), Alpha: \(a)")
}
请注意,如果在UIImage上使用它,这是UIImageView的属性,则像素坐标是原始分辨率的实际图像的坐标,而不是缩放的UIImageView的屏幕坐标。此外,它尝试使用RGB Jpg和RGBA PNG,并且两者都作为32位RGBA图像导入,因此它适用于两者。