package com.tuoheng.common.core.utils;

import net.coobird.thumbnailator.Thumbnails;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;

public class ThumbnailUtil {
    /**
     * 生成压缩图
     * @param url  原图地址
     * @param desFileSize 指定图片大小,单位kb
     * @param accuracy 精度,递归压缩的比率,建议小于0.9
     * @return
     */
    public static String cenerateCompression(String url,String urlThumbnail,long desFileSize , double accuracy){
        //String urlThumbnail= UploadFileConfig.uploadFolder +"Thumbnail"+ imgUrl;
        String root= urlThumbnail.substring(0,urlThumbnail.lastIndexOf("/"));
        //如果指定的文件夹不存在 则创建
        File filedir=new File(root);
            if (!filedir.exists()) {
                filedir.mkdirs();//创建文件夹
            }
            //图片文件
            File fileThumbnail = new File(urlThumbnail);
            if (fileThumbnail.exists()&&fileThumbnail.length() <= desFileSize * 1024) {
                System.out.println("已存在压缩文件！");
                return urlThumbnail;
            }
            //原图
            File file = new File(url);
            if (!file.exists() || !file.isFile()) {
                System.out.println("文件不存在");
            }
            try {
                if(!fileThumbnail.exists()) {
                    copyFileUsingFileStreams(file, new File(urlThumbnail));
                }
            }catch (IOException e){
                e.printStackTrace();
            }
            urlThumbnail = commpressPicForScale(url, urlThumbnail, desFileSize, accuracy);
        return urlThumbnail;
    }

    /**
     *
     * @param srcPath 原图片地址
     * @param desPath 目标图片地址
     * @param desFileSize 指定图片大小,单位kb
     * @param accuracy 精度,递归压缩的比率,建议小于0.9
     * @return
     */
    public static String commpressPicForScale(String srcPath,String desPath,
                                              long desFileSize , double accuracy){
        try {
            File srcFile = new File(srcPath);
            long srcFilesize = srcFile.length();
            System.out.println("原图片:"+srcPath + ",大小:" + srcFilesize/1024 + "kb");
            //递归压缩,直到目标文件大小小于desFileSize
            commpressPicCycle(desPath, desFileSize, accuracy);

            File desFile = new File(desPath);
            System.out.println("目标图片:" + desPath + ",大小" + desFile.length()/1024 + "kb");
            System.out.println("图片压缩完成!");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return desPath;
    }
    public static void commpressPicCycle(String desPath , long desFileSize,
                                         double accuracy) throws IOException{
        File imgFile = new File(desPath);
        long fileSize = imgFile.length();
        //判断大小,如果小于desFileSizek,不压缩,如果大于等于desFileSizek,压缩
        if(fileSize <= desFileSize * 1024){
            return;
        }
        //计算宽高
        BufferedImage bim = ImageIO.read(imgFile);
        int imgWidth = bim.getWidth();
        int imgHeight = bim.getHeight();
        int desWidth = new BigDecimal(imgWidth).multiply(
                new BigDecimal(accuracy)).intValue();
        int desHeight = new BigDecimal(imgHeight).multiply(
                new BigDecimal(accuracy)).intValue();
        Thumbnails.of(desPath).size(desWidth, desHeight).outputQuality(accuracy).toFile(desPath);
        //如果不满足要求,递归直至满足小于1M的要求
        commpressPicCycle(desPath, desFileSize, accuracy);
    }

    private static void copyFileUsingFileStreams(File source, File dest)
            throws IOException {
        InputStream input = null;
        OutputStream output = null;
        try {
            input = new FileInputStream(source);
            output = new FileOutputStream(dest);
            byte[] buf = new byte[1024];
            int bytesRead;
            while ((bytesRead = input.read(buf)) > 0) {
                output.write(buf, 0, bytesRead);
            }
        } finally {
            input.close();
            output.close();
        }
    }


}
