美文网首页
Swift 图片灰度化

Swift 图片灰度化

作者: LJ的ios开发 | 来源:发表于2017-01-12 18:13 被阅读144次
    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)
        }
    }
    

    相关文章

      网友评论

          本文标题:Swift 图片灰度化

          本文链接:https://www.haomeiwen.com/subject/qtcjbttx.html