Java获取图片颜色占比

该代码段实现了一个工具类`ImageColorUtil`,用于读取图片并分析其主要颜色分布。它通过读取图片,计算每个像素的颜色,并统计各颜色出现的频率,最后返回占比最高的指定数量的颜色及其比例。主要涉及图像处理、颜色分析和数据统计。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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 {

    /**
     * 获取占比最高的颜色及其占比
     *
     * @param file 图片文件
     * @param num  返回颜色数量
     * @return <颜色,<数量,比例>>
     */
    private static Map<String, Pair<Integer, Double>> colorRate(File file, int num) {
        Map<String, Pair<Integer, Double>> 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<Integer, Double> 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<String, Pair<Integer, Double>> stringPairMap = colorRate(file, 10);
        System.out.println(stringPairMap);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值