iOS图片与像素

我们知道图片的格式有很多种,如主流的png,jpg。这些格式指什么呢,指的是对图片的bitemap裸数据的压缩格式,压缩格式和压缩百分比的不同会导致图像大小和质量有差别。

说到bitmap,bitemap是什么呢?bitmap就是由一个一个像素组成的,每个像素又有可以看作是一个color,例如一张3024x4032的图片,转成bitemap之后有多大呢?一个像素大小为4个字节(rbga),得大小为:46M,而原图片大小一般为2M左右,增大了足足23倍,由此可见压缩格式的重要性。

知道了bitmap是什么,下面来看看,如何将一张图片转成bitmap或者UIColor的数组
这里提供两种方法:
方法一:通过CGImage的dataProvider

func pixelsOfImage(_ image: UIImage) -> [[UIColor]] {
        // 转CGImage
        guard let inputCGImage = image.cgImage else {
            return []
        }
        
        var bitmapData = inputCGImage.dataProvider!.data! as Data
        
        // 图片宽
        let width = inputCGImage.width
        // 图片高
        let height = inputCGImage.height
        
        let pixels = bitmapData.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer<UInt8>) -> UnsafeMutablePointer<UInt8> in
            return bytes
        }
        var currentPixel = pixels
        
        // 图片通道模型
        var colors: [[UIColor]] = []
        for _ in 0 ..< height
        {
            var rowColors: [UIColor] = []
            for _ in 0 ..< width
            {
                let r = currentPixel.pointee
                let g = (currentPixel + 1).pointee
                let b = (currentPixel + 2).pointee
                let a = (currentPixel + 3).pointee
                let color = UIColor(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: CGFloat(a)/255.0)
                rowColors.append(color)
                currentPixel += 4
            }
            colors.append(rowColors)
        }
        return colors
    }

方法二:通过CGContext生成像素数据

func pixelsOfImage1(_ image: UIImage) -> [[UIColor]] {
        // 转CGImage
        guard let inputCGImage = image.cgImage else {
            return []
        }
        
        // 图片宽
        let width = inputCGImage.width
        // 图片高
        let height = inputCGImage.height
        
        // 每像素字节数 32位图为4
        let bytesPerPixel = 4
        // 每个颜色通道大小
        let bitsPerComponent = 8
        // 每行大小
        let bytesPerRow = bytesPerPixel * width

        let pixels = UnsafeMutablePointer<UInt8>.allocate(capacity: width * height * bytesPerPixel)

        // 创建一个RGB模式的颜色空间CGColorSpace
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        // 创建CGBitmapContext容器,将像素指针参数传递到容器中缓存进行存储。

        let context = CGContext(data: pixels, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)
        // 绘制
        context?.draw(inputCGImage, in: CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height)))
        
        var currentPixel = pixels
        
        // 图片通道模型
        var colors: [[UIColor]] = []
        for _ in 0 ..< height
        {
            var rowColors: [UIColor] = []
            for _ in 0 ..< width
            {
                let r = currentPixel.pointee
                let g = (currentPixel + 1).pointee
                let b = (currentPixel + 2).pointee
                let a = (currentPixel + 3).pointee
                let color = UIColor(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: CGFloat(a)/255.0)
                rowColors.append(color)
                currentPixel += 4
            }
            colors.append(rowColors)
        }
        return colors
    }

那么又如何将bitemap数据转回去一张图片呢

func imageOfColors(_ colors: [[UIColor]]) -> UIImage {
        let rows = colors.count
        let cols = colors.first!.count
        let totalCount = rows * cols
        let pixelBytes =  UnsafeMutablePointer<UInt8>.allocate(capacity: totalCount * 4)
        //一个一个写进去rgba
        //当前指针
        var currentPoint = pixelBytes
        for row in 0 ..< rows
        {
            for col in 0 ..< cols
            {
                let color = colors[row][col]
                let rgba = color.cgColor.components
                //rgba
                for i in 0 ..< 4
                {
                    (currentPoint + i).pointee = UInt8(rgba![i] * 255)
                }
                currentPoint += 4
            }
        }
        
        //将bytes转化为image
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let ctx = CGContext.init(data: pixelBytes, width: cols, height: rows, bitsPerComponent: 8, bytesPerRow: 4 * cols, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)
        let cgimg = ctx!.makeImage()
        pixelBytes.deallocate()
        return UIImage(cgImage: cgimg!)
    }

我们可以利用上诉的一些方法去做一些事情,例如:如何将鸭子的黄色颜色部分变为红色?
看看效果图:


IMG_6886.jpg
IMG_6887.jpg
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容