【问题标题】:CIImage to UIImage Distorts Color SWIFTCIImage 到 UIImage 扭曲颜色 SWIFT
【发布时间】: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)
}

【问题讨论】:

    标签: swift uiimage ciimage


    【解决方案1】:

    所以我的转换函数没有正确初始化 CIContext。这是更正的方法:

      func convert(ciImage:CIImage) -> UIImage?
      {
        let context = CIContext(options: [CIContextOption.workingColorSpace: kCFNull!])
        if let cgImage:CGImage = context.createCGImage(ciImage, from: ciImage.extent, format: .RGBA8, colorSpace: CGColorSpace.init(name: CGColorSpace.sRGB)!) {
          let image:UIImage = UIImage.init(cgImage: cgImage)
          return image
        }
        return nil
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-10
      • 1970-01-01
      • 2013-01-15
      • 2017-12-02
      • 2012-08-02
      • 2020-12-30
      • 2017-02-11
      相关资源
      最近更新 更多