package shop.alien.util.image;

import com.luciad.imageio.webp.WebPReadParam;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * webp图片格式转换
 *
 * @author ssk
 * @version 1.0
 * @date 2023/5/6 9:43
 */
@Slf4j
public class WebpConvertUtil {

    public static void main(String[] args) throws IOException {
        String jpg = webpConvertWithLocalPath("C:\\Users\\Administrator\\Pictures\\Camera Roll\\1.webp", "jpg");
        System.out.println(jpg);
    }

    /**
     * 获取本地webp文件转jpg/png到同文件夹
     *
     * @param filePath    文件路径
     * @param convertType 转换格式(jpg,png)
     * @return 新文件名
     */
    public static String webpConvertWithLocalPath(String filePath, String convertType) {
        try {
            //源文件路径+名+.
            String sourceFilePath = filePath.substring(0, filePath.lastIndexOf(".") + 1);
            File webpFile = new File(filePath);
            ImageReader reader = ImageIO.getImageReadersByMIMEType("image/webp").next();
            WebPReadParam readParam = new WebPReadParam();
            readParam.setBypassFiltering(true);
            reader.setInput(new FileImageInputStream(webpFile));
            BufferedImage image = reader.read(0, readParam);
            //源文件路径+新格式
            File targetFile = new File(sourceFilePath + convertType);
            ImageIO.write(image, convertType, targetFile);
            return targetFile.getName();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    /**
     * 输入流Webp转jpg/png
     *
     * @param inputStream 输入流
     * @param convertType 转换类型
     * @return InputStream
     */
    public static InputStream webpConvertWithStream(InputStream inputStream, String convertType) {
        try {
            ByteArrayOutputStream bs = new ByteArrayOutputStream();
            ImageOutputStream imOut = ImageIO.createImageOutputStream(bs);
            ImageReader reader = ImageIO.getImageReadersByMIMEType("image/webp").next();
            WebPReadParam readParam = new WebPReadParam();
            readParam.setBypassFiltering(true);
            ImageInputStream iis = ImageIO.createImageInputStream(inputStream);
            reader.setInput(iis);
            BufferedImage image = reader.read(0, readParam);
            ImageIO.write(image, convertType, imOut);
            return new ByteArrayInputStream(bs.toByteArray());
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }
}