UIImage 到 UIColor 像素颜色数组 [英] UIImage to UIColor array of pixel colors

查看:25
本文介绍了UIImage 到 UIColor 像素颜色数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉问这个问题,但我不知道如何将 UIImage 表示为每个像素的 UIColor 数组.我已尽力转换 UIImagePNG/JPEGRepresentation,但无法获得所需的结果.

I'm sorry to ask this, but I can't figure out how to represent a UIImage as an array of UIColor for each pixel. I've tried my best with converting UIImagePNG/JPEGRepresentation but couldn't get the desired result.

推荐答案

这只是 Swift 对 Olie 的回答 的翻译ObjC 中的相同问题.确保你也给他一个赞.

This is simply a Swift's translation of Olie's answer to the same question in ObjC. Make sure you give him an upvote as well.

extension UIImage {
    func colorArray() -> [UIColor] {
        let result = NSMutableArray()

        let img = self.CGImage
        let width = CGImageGetWidth(img)
        let height = CGImageGetHeight(img)
        let colorSpace = CGColorSpaceCreateDeviceRGB()

        var rawData = [UInt8](count: width * height * 4, repeatedValue: 0)
        let bytesPerPixel = 4
        let bytesPerRow = bytesPerPixel * width
        let bytesPerComponent = 8

        let bitmapInfo = CGImageAlphaInfo.PremultipliedLast.rawValue | CGBitmapInfo.ByteOrder32Big.rawValue
        let context = CGBitmapContextCreate(&rawData, width, height, bytesPerComponent, bytesPerRow, colorSpace, bitmapInfo)

        CGContextDrawImage(context, CGRectMake(0, 0, CGFloat(width), CGFloat(height)), img);
        for x in 0..<width {
            for y in 0..<height {
                let byteIndex = (bytesPerRow * x) + y * bytesPerPixel

                let red   = CGFloat(rawData[byteIndex]    ) / 255.0
                let green = CGFloat(rawData[byteIndex + 1]) / 255.0
                let blue  = CGFloat(rawData[byteIndex + 2]) / 255.0
                let alpha = CGFloat(rawData[byteIndex + 3]) / 255.0

                let color = UIColor(red: red, green: green, blue: blue, alpha: alpha)
                result.addObject(color)
            }
        }

        return (result as NSArray) as! [UIColor]
    }
}

请注意,这运行得相当慢.模拟器解码 15MP 图像需要 35 秒,这是在四核 i7 上.

Note that this runs rather slowly. It takes 35 seconds for the simulator to decode a 15MP image, and that's on a quad-core i7.

这篇关于UIImage 到 UIColor 像素颜色数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆