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在計算機中所占的字節(jié)
        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)
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容