package cn.com.qmth.stmms.ms.commons.utils.image;

import cn.com.qmth.stmms.ms.commons.config.ImageCompressionConfig;
import net.coobird.thumbnailator.Thumbnails;

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

/**
 * 图片压缩
 * Created by zhengmin on 2016/11/18.
 */
public class ImageCompression {

    /**
     * 分辨率压缩
     *
     * @param in 图片文件输入流
     * @return
     * @throws IOException
     */
    public static BufferedImage compress(File in, ImageCompressionConfig config) throws IOException {
        if (config == null) {
            return ImageIO.read(in);
        }
        BufferedImage image = ImageIO.read(in);
        int originWidth = image.getWidth();
        int originHeight = image.getHeight();
        int sizeWidth = config.getMinWith();
        int sizeHeight = config.getMinHeight();

        if (config.getPercent() != null && config.getPercent() > 0 && config.getPercent() <= 100) {
            float percent = (float) config.getPercent() / 100;
            sizeWidth = (int) (sizeWidth * percent);
            sizeHeight = (int) (sizeHeight * percent);
            if (sizeWidth < config.getMinWith()) {
                sizeWidth = config.getMinWith();
            }
            if (sizeHeight < config.getMinHeight()) {
                sizeHeight = config.getMinHeight();
            }
        }

        int width = sizeWidth;
        int height = sizeHeight;


        if (originWidth < originHeight) {
            width = sizeHeight;
            height = sizeWidth;
        }
        return Thumbnails.of(image)
                .size(width, height)
                .outputQuality(1f)
                .outputFormat("jpg")
                .asBufferedImage();
    }

    public static void rotate(File in, File out, int degree) throws IOException {
        BufferedImage image = ImageIO.read(in);
        Thumbnails.of(image).scale(1f).outputQuality(1f).rotate(degree).outputFormat("jpg").toFile(out);
    }

    public static void imageThumbnail(File in, File out, ImageCompressionConfig config) throws IOException {
        if (config == null) {
            Thumbnails.of(in).scale(1f).outputQuality(1f).outputFormat("jpg").toFile(out);
            return;
        }
        BufferedImage image = ImageIO.read(in);
        int originWidth = image.getWidth();
        int originHeight = image.getHeight();
        int sizeWidth = config.getMinWith();
        int sizeHeight = config.getMinHeight();
        int width = sizeWidth;
        int height = sizeHeight;
        if (originWidth < originHeight) {
            width = sizeHeight;
            height = sizeWidth;
        }
        Thumbnails.of(in).size(width, height).outputQuality(1f).outputFormat("jpg").toFile(out);
    }
}
