• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

JS 简单获取本地图片主色调

武飞扬头像
头疼脑胀的代码搬运工
帮助191

废话开篇:想象一个场景,就是如何根据一张图片大概提取出它的主色调呢?获取主色调后,可能会用来设置某些背景颜色,这里,利用 JS 简单获取本地图片主色调

一、实现效果

鲜花

大海

森林

二、实现

1、实现思路

其实思路很简单,就是将一张大图先缩小为一张小图,再遍历里面的像素,找到出现次数相对较高的一个;当然,先说明一下,这个也只能实现一个提取近似的值或者跟“人的意识”相反的值,因此,最终结果的“满意程度”可能不是很好。

2、实现代码

创建一个 ThemeColor 操作对象,通过回调返回缩略图主色调 ,可进行相关的其他操作

//本地图片资源
let url = 'tree.webp'
document.getElementById('originalImage').src = url
let themeColor = new ThemeColor(url,(shrinkUrl,color)=>{
    //缩略图
    let img = document.getElementById('showImage')
    if(img){
        img.setAttribute('src',shrinkUrl)
    }
    //主色
    document.getElementById('showDiv').style.backgroundColor = color
})

ThemeColor.js

class ThemeColor{
    // 原图资源
    imgUrl = ''
    // 像素集合
    originalPiexls = null
    // 缩略图
    shrinkUrl = ''
    // 主色
    themeColor = 'white'
    // 回调
    themeColorCallBack = null
    // 提取像素出现最大次数操作对象
    colorCountedSet = new ColorCountedSet()
    
    constructor(imgUrl,callBack){
        this.imgUrl = imgUrl
        this.themeColorCallBack = callBack
        this.startScreeningThemeColor()
    }
    
    // 开始解析主色
    async startScreeningThemeColor(){
        try {
            await this.shrinkImage()
        } catch (error) {
            console.log('error:'   error)
        }
        this.screeningThemeColor()
    }

    // 图片缩小
    async shrinkImage(){
        var image = new Image();
        image.src = this.imgUrl;
        await new Promise((resolve)=>{
            image.onload = resolve
        })
        let width = image.width
        let height = image.height
        let shrinkFactor = 10
        let shrinkWidth = width / shrinkFactor
        let shrinkHeight = height / shrinkFactor
        let canvas = document.createElement('canvas')
        canvas.setAttribute('width',`${shrinkWidth}px`)
        canvas.setAttribute('height',`${shrinkHeight}px`)
        var ctx = canvas.getContext("2d")
        ctx.drawImage(image,0,0,shrinkWidth,shrinkHeight)
        this.shrinkUrl = canvas.toDataURL('image/jpeg',1)
        try {
            //保存像素
            this.originalPiexls = ctx.getImageData(0,0,width,height)
        } catch (error) {
            console.log(error)
        }
    }

    // 开始筛选主题色
    screeningThemeColor(){
        if(!this.originalPiexls || !this.originalPiexls.data || this.originalPiexls.data.length == 0){
            throw('像素为空')
        }
        for(let i = 0;i < this.originalPiexls.data.length;i =4){
            let r = this.originalPiexls.data[i]
            let g = this.originalPiexls.data[i   1]
            let b = this.originalPiexls.data[i   2]
            let a = this.originalPiexls.data[i   3] / 255.0
            //添加一个色值范围,让它能忽略一定无效的像素值
            if(a > 0 && (r < 200 && g < 200 && b < 200) && (r > 50 && g > 50 && b > 50)){
                this.colorCountedSet.push(r,g,b,a)
            }
        }

        let maxCount = 0
        // 寻找出现次数最多的像素定为主色调
        this.colorCountedSet.forEach((value,key)=>{
            if(maxCount <= value){
                maxCount = value
                this.themeColor = 'rgba('   key   ')'
            }
        })
        //执行回调
        if(this.themeColorCallBack){
            this.themeColorCallBack(this.shrinkUrl,this.themeColor)
        }
    }
 }

// 统计不同像素的出现次数
class ColorCountedSet{
    //像素集合
    map = new Map()
    
    //添加像素到集合
    push(r,g,b,a){
        //根据像素值生成一个map 元素 key值
        let identification = r   ','   g   ','   b   ','   a
        if(!this.map.get(identification)){
            this.map.set(identification,1)
        } else {
            // 存在进行次数自增
            let times = parseInt(this.map.get(identification))   1
            this.map.set(identification,times)
        }
    }

// 给 ColorCountedSet 操作类添加一个 forEach 方法 
forEach(cb){
        this.map.forEach(function(value,key){
                cb(value,key)
        });
    }
}

三、总结与思考

内容没什么特别复杂的,之前做移动端的时候有这么一个需求,其实实现的思路都是一样的,这里就是一个抛砖引玉的作用,希望能给需要的人提供一个思路,如果能帮助大家,深感欣慰,代码拙劣,大神勿笑[抱拳][抱拳][抱拳]

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanffabf
系列文章
更多 icon
同类精品
更多 icon
继续加载