【发布时间】:2020-09-17 21:04:31
【问题描述】:
我遇到了一个问题,我从 CIImage => UIImage 转换了图像,并且颜色在转换的某处变得扭曲。
我设置的测试用例是一个纯蓝色的图像,我用 CIImage 和一个指向路径的 url 打开它。我使用我认为将 CIImage 转换为 UIImage 的非常标准的方法将其转换为 UIImage,即 CIContext:createCGImage,然后检查其中一个像素。
预期:
pixelColor :: rgba : 0.0 : 0.0 : 1.0 : 1.0
实际:
pixelColor :: rgba : 0.0 : 0.1803921568627451 : 1.0 : 1.0
无论如何,如果有人能指出为什么会发生这种情况,我将不胜感激。谢谢。
guard let path = Bundle.main.path(forResource: "Blue", ofType: "png") else { // RGBA 0, 0, 255, 0
debugPrint("File :: Blue not found")
return
}
let url = URL(fileURLWithPath: path)
if let ciImage = CIImage(contentsOf: url) {
let converted = convert(ciImage: ciImage)
let _ = converted.getPixelColor(pos: pixelPoint)
}
--
func convert(ciImage:CIImage) -> UIImage
{
let context:CIContext = CIContext.init(options: nil)
let cgImage:CGImage = context.createCGImage(ciImage, from: ciImage.extent)!
let image:UIImage = UIImage.init(cgImage: cgImage)
return image
}
--
extension UIImage {
func getPixelColor(pos: CGPoint) -> UIColor {
let pixelData = self.cgImage!.dataProvider!.data
let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
let pixelInfo: Int = ((Int(self.size.width) * Int(pos.y)) + Int(pos.x)) * 4
let r = CGFloat(data[pixelInfo]) / CGFloat(255.0)
let g = CGFloat(data[pixelInfo+1]) / CGFloat(255.0)
let b = CGFloat(data[pixelInfo+2]) / CGFloat(255.0)
let a = CGFloat(data[pixelInfo+3]) / CGFloat(255.0)
print("pixelColor :: rgba : \(r) : \(g) : \(b) : \(a)")
return UIColor(red: r, green: g, blue: b, alpha: a)
}
【问题讨论】: