package com.ruoyi.test;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.img.Img;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.esotericsoftware.kryo.io.Input;
import org.junit.jupiter.api.Test;


import javax.swing.*;
import java.awt.image.BufferedImage;
import java.io.*;


public class ImageTest {



    @Test
    public void test1(){
        JFileChooser jfc = new JFileChooser();
        jfc.setMultiSelectionEnabled(true);
        jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        jfc.showOpenDialog(null);
        File[] fs = jfc.getSelectedFiles();
        for(File f : fs) {
            File outFile = new File(f.getAbsolutePath().substring(0,f.getAbsolutePath().lastIndexOf("."))+".webp");
            try(
                InputStream in = formatImage(Img.from(f),800,800,null);
                OutputStream out = new FileOutputStream(outFile);
                ){
                IoUtil.copy(in,out);
            }catch (Exception e){

            }

        }
    }



    public InputStream formatImage(Img img, int maxWidth, int maxHeight, BufferedImage watermark) {
        try {
            int w = img.getImg().getWidth(null);
            int h = img.getImg().getHeight(null);
            if(maxWidth>0 && maxHeight > 0){
                if (w > maxWidth || h > maxHeight) {
                    int outWidth = 0;
                    int outHeight = 0;
                    outHeight = maxWidth * h / w;
                    if (outHeight > maxHeight) {
                        outHeight = maxHeight;
                        outWidth = outHeight * maxWidth / h;
                    } else {
                        outWidth = maxWidth;
                    }
                    img = img.scale(outWidth, outHeight);
                    w = outWidth;
                    h = outHeight;
                }
            }

            if (watermark != null) {
                int ww = watermark.getWidth(null);
                int wh = watermark.getHeight(null);
                if (w > ww && h > wh) {
                    img = img.pressImage(watermark, 0, 0, 1f);
                }
            }

            ByteArrayOutputStream pout = new ByteArrayOutputStream();

            img.setTargetImageType("webp").write(pout);

            ByteArrayInputStream pin = new ByteArrayInputStream(pout.toByteArray());
            pout.close();
            pout = null;
            return pin;
        } catch (Exception e) {
            throw new RuntimeException("处理图片错误", e);
        }
    }


    @Test
    public void base64()throws Exception {
      String base = Base64.encode(new File("D:\\nextcloud\\微信材料\\微信图片_20231027143520.jpg"));
      FileUtil.writeString(base,new File("/data"),"utf-8");
    }
}
