package com.example.jmacro.wjdr.util;

import cn.hutool.core.img.ImgUtil;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 图片加载器
 */
public class Imager {

    private final static Map<String, BufferedImage> cache = new HashMap();

    /**
     * 加载图片
     *
     * @param pic 图片
     * @return 缓冲区图像
     */
    public static BufferedImage load(File pic) {
        if (cache.containsKey(pic.getAbsolutePath())) {
            return cache.get(pic.getAbsolutePath());
        }
        BufferedImage read = ImgUtil.read(pic);
        cache.put(pic.getAbsolutePath(), read);
        return read;
    }

    /**
     * 加载多个图片
     *
     * @param pics 图片集
     * @return 缓冲区图像集
     */
    public static BufferedImage[] load(File[] pics) {
        BufferedImage[] images = new BufferedImage[pics.length];
        for (int i = 0; i < images.length; i++) {
            images[i] = load(pics[i]);
        }
        return images;
    }

    /**
     * 加载多个图片
     *
     * @param pics 图片集
     * @return 缓冲区图像集
     */
    public static List<BufferedImage> load(List<File> pics) {
        List<BufferedImage> images = new ArrayList();
        for (File file : pics) {
            images.add(load(file));
        }
        return images;
    }

    public static int[][] getImageRGB(BufferedImage bfImage) {
        int width = bfImage.getWidth();
        int height = bfImage.getHeight();
        int[][] result = new int[width][height];
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                // 对某个像素点的RGB编码并存入数据库
                result[x][y] = bfImage.getRGB(x, y);
                // 单独获取每一个像素点的Alpha, Red，Green，和Blue的值。
                // int a = rgb>>24 & 0xff;
                // int r = rgb>>16 & 0xff;
                // int g = rgb>>8 & 0xff;
                // int b = rgb & 0xff;
            }
        }
        return result;
    }

    /**
     * 计算图片相似度
     *
     * @param x
     * @param y
     * @param smallHeight
     * @param smallWidth
     * @param bigData
     * @param smallData
     * @return
     */
    public static double calcSimilar(int x, int y, int smallHeight, int smallWidth, int[][] bigData, int[][] smallData) {
        int similar = 0;
        for (int smallY = 0; smallY < smallHeight; smallY++) {
            for (int smallX = 0; smallX < smallWidth; smallX++) {
                if (ColorUtil.isSimilar(bigData[x + smallX][y + smallY], smallData[smallX][smallY])) {
                    similar++;
                }
            }
        }
        return (double) similar / (smallWidth * smallHeight);
    }
}
