Swift 图片灰度化

extension UIImage {
    
    func lj_grayScale() -> UIImage?{
        guard let imageCG = self.cgImage else {
            return nil
        }
        let width = imageCG.width
        let height = imageCG.height
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        // 申请内存空间
        let pixels = UnsafeMutablePointer<UInt32>.allocate(capacity: width * height )
        //UInt32在计算机中所占的字节
        let uint32Size = MemoryLayout<UInt32>.size
        let context = CGContext.init(data: pixels,
                                width: width,
                                height: height,
                                bitsPerComponent: 8,
                                bytesPerRow: uint32Size * width,
                                space: colorSpace,
                                bitmapInfo: CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue)
        
        context?.draw(imageCG, in: CGRect(x: 0, y: 0, width: width, height: height))
        for y in 0 ..< height {
            for x in 0 ..< width {
                let rgbaPixel = pixels.advanced(by: y * width + x)
                //类型转换 -> UInt8
                let rgb = unsafeBitCast(rgbaPixel, to: UnsafeMutablePointer<UInt8>.self)
                // rgba 所在位置 alpha 0, blue  1, green 2, red 3
                let gray = UInt8(0.3  * Double(rgb[3]) +
                                 0.59 * Double(rgb[2]) +
                                 0.11 * Double(rgb[1]))
                rgb[3] = gray
                rgb[2] = gray
                rgb[1] = gray
            }
        }
        guard let image = context?.makeImage() else {
            return nil
        }
        pixels.deallocate(capacity: width * height)
        return UIImage(cgImage: image, scale: 0, orientation: self.imageOrientation)
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容