package shop.alien.util.image;

import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 图片工具类
 *
 * @author ssk
 * @version 1.0
 * @date 2023/1/17 9:28
 */
@Slf4j
public class ImageUtil {

    public static void main(String[] args) {
        System.out.println(getImageSizeInfo("C:\\Users\\17238\\Pictures\\Saved Pictures\\4255d6629aa94ff3926fed0bc43684dd_noop.jpg"));
    }

    /**
     * 获取图片尺寸信息
     *
     * @param path 路径
     * @return Map
     */
    public static Map<String, Object> getImageSizeInfo(String path) {
        try {
            if (null != path && !"".equals(path)) {
                Map<String, Object> map = new HashMap<>();
                // 文件对象
                File file = new File(path);
                // 文件大小；其中file.length()获取的是字节，除以1024可以得到以kb为单位的文件大小
                double size = file.length() / 1024.0;
                BigDecimal bigDecimal = new BigDecimal(size);
                size = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                map.put("size", size);
                // 图片对象
                BufferedImage bufferedImage = ImageIO.read(new FileInputStream(file));
                // 宽度
                int width = bufferedImage.getWidth();
                map.put("width", width);
                // 高度
                int height = bufferedImage.getHeight();
                map.put("height", height);
                return map;
            }
            return null;
        } catch (Exception e) {
            log.error("ImageUtil/getImageSizeInfo ERROR Msg = {}", e.getMessage());
            return null;
        }
    }
}
