首页 > 解决方案 > 将作为图像 URL 的字符串转换为字节数组

问题描述

我有一个来自 Spring RestTemplateget结果的图像内容:

String url = "https://is2-ssl.mzstatic.com/image/" +
        "thumb/Purple114/v4/15/a1/68/15a1681f-dec4-b01f-4362" +
        "-e9ff1ece9c09/AppIcon-1x_U007emarketing-0-10-0-0-85" +
        "-220-0.png/60x60bb.png";
String imageAsString = restTemplate.getForObject(url, String.class);

我知道这不是通过RestTemplate. 但我应该为我的旧代码保留它。

如何将此值转换为正确的图像字节数组格式?

imageAsString.getBytes()-> 这不一样restTemplate.getForObject(url, byte[].class);

标签: javaarraysimagefileresttemplate

解决方案


如果你有一个 image URL,你可以先把read它变成 a BufferedImage,然后再把write它变成 a FileOutputStream,如下所示:

public static void main(String[] args) throws IOException {
    URL url = new URL("https://is2-ssl.mzstatic.com/image/" +
            "thumb/Purple114/v4/15/a1/68/15a1681f-dec4-b01f-4362" +
            "-e9ff1ece9c09/AppIcon-1x_U007emarketing-0-10-0-0-85" +
            "-220-0.png/60x60bb.png");

    BufferedImage bufferedImage = ImageIO.read(url);

    ImageIO.write(bufferedImage, "png",
            new FileOutputStream("resources/bufferedImage.png"));
}

这是图像:bufferedImage.png

缓冲图像.png


推荐阅读