Spring RestTemplate - 读取PNG标头的I / O错误

时间:2014-11-20 18:28:33

标签: spring spring-mvc resttemplate

我正在对外部应用程序进行API调用(此应用程序将最初加载到其中的所有图像转换为PNG)。 如果图像最初作为PNG加载到该应用程序中,则RestTemplate可以正常运行。如果它最初被加载为其他东西然后转换为PNG,则下面的代码在Spring 4.1.1中尝试使用RestTemplate时会抛出错误。外部应用程序上的图像显示正常。

  

引起:javax.imageio.IIOException:读取PNG标头的I / O错误!       在com.sun.imageio.plugins.png.PNGImageReader.readHeader(PNGImageReader.java:315)〜[na:1.8.0_20]       在com.sun.imageio.plugins.png.PNGImageReader.readMetadata(PNGImageReader.java:654)〜[na:1.8.0_20]       at com.sun.imageio.plugins.png.PNGImageReader.readImage(PNGImageReader.java:1248)~ [na:1.8.0_20]       在com.sun.imageio.plugins.png.PNGImageReader.read(PNGImageReader.java:1606)〜[na:1.8.0_20]       在org.springframework.http.converter.BufferedImageHttpMessageConverter.read(BufferedImageHttpMessageConverter.java:174)〜[BufferedImageHttpMessageConverter.class:4.1.1.RELEASE]       在org.springframework.http.converter.BufferedImageHttpMessageConverter.read(BufferedImageHttpMessageConverter.java:67)〜[BufferedImageHttpMessageConverter.class:4.1.1.RELEASE]       在org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:104)〜[HttpMessageConverterExtractor.class:4.1.1.RELEASE]       在org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:576)〜[RestTemplate.class:4.1.1.RELEASE]       ...省略了74个常用帧   引起:javax.imageio.IIOException:错误的PNG签名!       在com.sun.imageio.plugins.png.PNGImageReader.readHeader(PNGImageReader.java:242)〜[na:1.8.0_20]

BufferedImage image = restTemplate.getForObject(getPhotoUrl(), BufferedImage.class, Collections.EMPTY_MAP);

1 个答案:

答案 0 :(得分:1)

使用exchange方法获取字节数组,而不是使用getForObject方法获取BufferedImage。现在,浏览器中会显示包含错误PNG标题的图像。

//Set HttpHeaders object
List<MediaType> acceptableMediaTypes = new ArrayList<>();
acceptableMediaTypes.add(MediaType.IMAGE_PNG);
HttpHeaders headers = new HttpHeaders();
headers.setAccept(acceptableMediaTypes);

//Get image from external app with API call
ResponseEntity<byte[]> responseEntity = restTemplate.exchange(getPhotoUrl(), HttpMethod.GET, new HttpEntity<byte[]>(headers), byte[].class);
byte[] image = responseEntity.getBody();

//Display image in browser
if(image != null) {
    InputStream in = new ByteArrayInputStream(image);
    BufferedImage bImageFromConvert = ImageIO.read(in);

    if(bImageFromConvert != null) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(bImageFromConvert, "png", baos);
        byte[] data = baos.toByteArray();
        response.setContentType(MediaType.IMAGE_PNG_VALUE);
        response.getOutputStream().write(data);
    }
}