如何将webp转成到png、jpg等格式

直接上代码

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class WebPToMultipartFileConverter {

    public static MultipartFile downloadAndConvertWebPToMultipartFile(String fileUrl, String formatName) throws IOException {
        String localWebPPath = "downloaded_image.webp"; // 下载的WebP文件本地路径
        String outputFilePath = "converted_image." + formatName; // 转换后的文件路径

        // 步骤1:下载文件
        URL url = new URL(fileUrl);
        try (InputStream in = url.openStream()) {
            Files.copy(in, Paths.get(localWebPPath), StandardCopyOption.REPLACE_EXISTING);
        }

        File webPFile = new File(localWebPPath);
        File outputFile = new File(outputFilePath);
        try {
            // 步骤2:将WebP转换为JPG或PNG
            BufferedImage bufferedImage = ImageIO.read(webPFile);
            if (bufferedImage == null) {
                throw new IOException("无法读取下载的WebP文件。");
            }

            ImageIO.write(bufferedImage, formatName, outputFile);

            // 步骤3:将输出文件转换为MultipartFile
            FileItem fileItem = new DiskFileItemFactory().createItem("file", "image/" + formatName, false, outputFile.getName());

            try (FileInputStream input = new FileInputStream(outputFile)) {
                byte[] buffer = new byte[(int) outputFile.length()];
                input.read(buffer);
                fileItem.getOutputStream().write(buffer);
            }

            return new CommonsMultipartFile(fileItem);
        } finally {
            // 确保删除本地文件
            if (webPFile.exists()) {
                webPFile.delete();
            }
            if (outputFile.exists()) {
                outputFile.delete();
            }
        }
    }

    public static void main(String[] args) {
        String fileUrl = "https://xxx/533800b5-f3ed-4306-b985-020b6b87459c.webp";
        String formatName = "jpg"; // 或 "png"

        try {
            MultipartFile multipartFile = downloadAndConvertWebPToMultipartFile(fileUrl, formatName);
            System.out.println("MultipartFile: " + multipartFile.getName());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小码哥(xmgcode88)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值