栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java获取图片颜色占比

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java获取图片颜色占比

import cn.hutool.core.lang.Pair;
import cn.hutool.core.util.HexUtil;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.linkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
public class ImageColorUtil {

    
    private static Map> colorRate(File file, int num) {
        Map> result = new HashMap<>();
        int[] rgb = new int[3];
        BufferedImage bi = null;

        try {
            bi = ImageIO.read(file);
        } catch (IOException e) {
            log.error("read_img_fail", e);
        }

        if (bi == null) {
            return result;
        }

        int width = bi.getWidth();
        int height = bi.getHeight();
        int minx = bi.getMinX();
        int miny = bi.getMinY();


        int total = width * height;
        for (int i = minx; i < width; i++) {
            for (int j = miny; j < height; j++) {
                int pixel = bi.getRGB(i, j);
                rgb[0] = (pixel & 0xff0000) >> 16;
                rgb[1] = (pixel & 0xff00) >> 8;
                rgb[2] = (pixel & 0xff);

                String color = String.join("", "#", HexUtil.toHex(rgb[0]), HexUtil.toHex(rgb[1]), HexUtil.toHex(rgb[2])).toUpperCase();
                if (result.containsKey(color)) {
                    Pair numRate = result.get(color);
                    result.put(color, new Pair<>(numRate.getKey() + 1, (numRate.getKey() + 1) * 1.0 / total));
                } else {
                    result.put(color, new Pair<>(1, 0.0));
                }

            }
        }

        return result.entrySet().stream()
                .sorted(Map.Entry.comparingByValue((v1, v2) -> v2.getKey().compareTo(v1.getKey()))).limit(num)
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (v1, v2) -> v1, linkedHashMap::new));

    }

    public static void main(String[] args) {
        File file = new File(OcrProxy.readImg("https://isite.bj.bcebos.com/snapshot/09179782d12d69a87330778ea657c210"));
        Map> stringPairMap = colorRate(file, 10);
        System.out.println(stringPairMap);
    }

}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/272405.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号