package com.iformall.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ImgUtil {
    private final static Logger logger = LoggerFactory.getLogger(ImgUtil.class);

    /**
     * 图片瘦身
     * @param input
     * @param newFile
     * @param imgFormat png, jpg, gif
     * @throws Exception
     */
    public static File thinImage(String input, String newFile, String imgFormat) throws IOException {
        File file = new File(newFile);      // 输出到文件流
        File pDest = file.getParentFile();
        if (!pDest.exists()) {
            pDest.mkdirs();
        }
        Image src = ImageIO.read(new File(input));
        int width = src.getWidth(null);     // 获取图源宽度
        int height = src.getHeight(null);   // 获取图源高度
        BufferedImage thumb = new BufferedImage(width / 1, height / 1, BufferedImage.TYPE_INT_RGB);
        // 绘制缩小后的图
        thumb.getGraphics().drawImage(src, 0,  0, width / 1, height / 1, null);
        ImageIO.write(thumb, imgFormat, file);
        return file;
    }

    public static String getImgFormat(String fileFormat) {
        String imgFormat = "";
        if(fileFormat.equalsIgnoreCase(".jpg") || fileFormat.equalsIgnoreCase(".jpeg")) {
            imgFormat = "jpg";
        } else if(fileFormat.equalsIgnoreCase(".png")) {
            imgFormat = "png";
        }
        return imgFormat;
    }
}
