美文网首页
swift图片颜色占比分析

swift图片颜色占比分析

作者: joeal | 来源:发表于2018-08-30 14:24 被阅读47次

    swift图片颜色占比分析

    extension UIImage {
        func scaleTo(size: CGSize) -> UIImage? {
            UIGraphicsBeginImageContextWithOptions(size, false, 1.0)
            self.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
            let newImg = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return newImg
        }
        
        /// 一张图颜色占比 取十种颜色
        func colorRate() -> [Double] {
            // 把 UIImage 转换成 CGImage Data
            let provider = self.cgImage?.dataProvider
            let pixeData = provider?.data
            guard let pxData = pixeData else {
                return []
            }
            guard let data = CFDataGetBytePtr(pxData) else {
                return []
            }
            let dataLength = CFDataGetLength(pxData)
            let numberOfColorComponents = 4 // R,G,B, and A
            
            // 用来装 color ,key 为 R-G-B 字符串,value 为出现次数
            var colors = [String: Double]()
            var colorCount: Double = 0
            var i = 0
            while i < dataLength {
                i += numberOfColorComponents
                if data[i + 3] != 0 {//非透明
                    colorCount += 1
                    let red = data[i]
                    let green = data[i + 1]
                    let blue = data[i + 2]
                    let result = "\(red)-\(green)-\(blue)"
                    if !colors.keys.contains(result) {
                        colors[result] = 1
                    } else {
                        colors[result] = colors[result]! + 1.0
                    }
                }
            }
            
            let  colorValues = colors.values.sorted { $0 > $1 }
            var colorRates = [Double]()
            for (index, item) in colorValues.enumerated() {
                if index < 10 {
                    let rate = item / colorCount
                    colorRates.append(rate)
                }
            }
            return colorRates
        }
    }
    
    test3.jpg

    调用以上方法,终端输出:
    [0.3862848497311907, 0.093752754193718965, 0.088868650665413204, 0.088369223537706751, 0.018655072123152854, 0.017913275948177092, 0.011376656188489674, 0.0076897088633626131, 0.0057727900349598986, 0.0051558506419107494]

    相关文章

      网友评论

          本文标题:swift图片颜色占比分析

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