iOS: 如何从 Swift 中的 CGImage 获取像素数据数组

iOS: How to get pixel data array from CGImage in Swift

我需要从可以是 RGB8、RGB16、GRAYSCALE8 或 GRAYSCALE16 的 CGImage 中获取字节数组形式的像素数据。 this one 等以前的解决方案会产生暗淡或扭曲的图像。

根据您问题中提供的 link,您可以通过

获取像素数据
extension UIImage {
    func pixelData() -> [UInt8]? {
        let size = self.size
        let dataSize = size.width * size.height * 4
        var pixelData = [UInt8](repeating: 0, count: Int(dataSize))
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let context = CGContext(data: &pixelData,
                                width: Int(size.width),
                                height: Int(size.height),
                                bitsPerComponent: 8,
                                bytesPerRow: 4 * Int(size.width),
                                space: colorSpace,
                                bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)
        guard let cgImage = self.cgImage else { return nil }
        context?.draw(cgImage, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))

        return pixelData
    }
 }

但是,作为开发者,这里关注的对象是bitmapInfocolorSpace。根据提供的信息,您的图像可能会变形或颜色不同。确切的解决方案将取决于您如何获得图像以及图像提供的配色方案。您可能只需要使用变量。

我在使用 CGColorSpaceCreateDeviceRGB() 作为我的 colorSpace 时从未遇到过问题,但我不得不多次更改 bitmapInfo,因为我的图像以不同的值出现。

Here is the location to reference the different types of bitmaps. More than likely though, you only need a variation of the CGImageAlphaInfo which can be located here.

如有必要,您可以更改colorSpace。默认CGcolorSpace网页可以找到here. However, you could probably get away with one of the default ones located here