package org.jeecg.module.custom.ocr.utils;

import net.coobird.thumbnailator.Thumbnails;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * @Title:
 * @Description: 图片设置
 * @Author 郭向斌
 * @Date 2024-03-18 15:29
 * @Version V1.0
 */
public class ImageUtils {
    public static String generateThumbnail(String inputImagePath, Integer newWidth) throws IOException {
        if(newWidth==null){
            newWidth=182;
        }
        String directoryPath = inputImagePath.substring(0, inputImagePath.lastIndexOf("/") + 1);
        File inputFile = new File(inputImagePath);
        String outputImagePath = directoryPath+ "thumbnail_" + inputFile.getName();
        BufferedImage bufferedImage = Thumbnails.of(inputFile).scale(1).asBufferedImage();
        int width = bufferedImage.getWidth();
        int height = bufferedImage.getHeight();
        int newHeight = (int) Math.round((double) height * newWidth / width);

        Thumbnails.of(inputFile).size(newWidth, newHeight).outputFormat( getFileExtension(inputFile.getName())).toFile(new File(outputImagePath));
        return outputImagePath;
    }


    public static String getFileExtension(String fileName) {
        if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) {
            return fileName.substring(fileName.lastIndexOf(".") + 1);
        } else {
            return "jpg"; // 没有后缀名或者文件名以点号开头
        }
    }

    public static void main(String[] args) throws IOException {
        String url="C:\\Users\\郭向斌\\Downloads\\1-星浩.png";
        String s = generateThumbnail(url,180);
        System.out.println(s);
        String st="http://47.93.59.251/api/image/";
        String s1 = ImageUtils.generateThumbnail(url, 182);
        String stri=st+getFileName(s1);
        System.out.println(stri);
    }
    public static String getFileName(String filePath) {
        File file = new File(filePath);
        return file.getName();
    }
}
