java webp图片转jpg

如iphone11手机无法展示从tiktok拉取的webp格式的头像.
解决方法: 把拿到的头像转换成jpg格式, 然后再上传到服务器
 
 

Maven

<!-- https://mvnrepository.com/artifact/org.sejda.imageio/webp-imageio -->
        <dependency>
            <groupId>org.sejda.imageio</groupId>
            <artifactId>webp-imageio</artifactId>
            <version>0.1.6</version>
        </dependency>

调用

public String uploadTiktokLogo(String logoUrl) {
        HttpURLConnection conn = null;
        File webpFile = null;
        File jpgFile = null;
        try {
            URL url = new URL(logoUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5*1000);
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            InputStream inputStream = conn.getInputStream();
            webpFile = new File(picPath + WavelyStringUtils.getRandomStr() + ".webp");
            FileUtils.copyInputStreamToFile(inputStream, webpFile);

            /* Convert webp to jpg start */
            ImageReader reader = ImageIO.getImageReadersByMIMEType("image/webp").next();
            // configure decoding parameters
            WebPReadParam readParam = new WebPReadParam();
            readParam.setBypassFiltering(true);
            // configure the input on the ImageReader
            reader.setInput(new FileImageInputStream(webpFile));
            // Decode the image
            BufferedImage image = reader.read(0, readParam);
            // "jpg" can be "png" too
            jpgFile = new File(picPath + WavelyStringUtils.getRandomStr() + ".jpg");
            ImageIO.write(image, "jpg", jpgFile);
            /* Convert webp to jpg end */

            FileInputStream fileInputStream = new FileInputStream(jpgFile);
            MultipartFile multipartFile = new MockMultipartFile(jpgFile.getName(), jpgFile.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
            return ((Map<String, String>) uploadFile(0, multipartFile).getData()).get("fileUrl");
        } catch (Exception e) {
            logger.error("uploadLogo error, logoUrl:{}", logoUrl, e);
        } finally {
            FileUtils.deleteQuietly(webpFile);
            FileUtils.deleteQuietly(jpgFile);
            if(conn != null) conn.disconnect();
        }
        return "";
    }
posted @ 2022-01-28 22:00  wmxl  阅读(1289)  评论(0编辑  收藏  举报