Difference between image in web browser and image in Java

I have a PNG image coming from a URL (inside my company). When I navigate to this URL in my web browser, I see the image correctly (with transparency). I see from Chrome’s network tools that it returns as the image type / png mime as expected. I can save the image from the browser to a local hard drive, and it ends in about 32 KB.

I wrote a simple Java program to pull out an image and save it programmatically. The save image code is very simple, as shown below:

public static void saveImage(String imageUrl, String destinationFile) throws IOException { URL url = new URL(imageUrl); InputStream is = url.openStream(); OutputStream os = new FileOutputStream(destinationFile); byte[] b = new byte[2048]; int length; while ((length = is.read(b)) != -1) { os.write(b, 0, length); } is.close(); os.close(); } 

However, whenever I run this program, the saved image is distorted. As a result, it looks about the same, except for a loss of transparency. Its size is only about 4 kilobytes. In addition to this, just looking at the bytes, I see that the first 3 bytes are "GIF".

Can anyone help me understand what makes the difference?

(Note: The image URL that I use in both cases actually points to a Java web application that uses ImageIO.read to return a BufferedImage from the actual image URL.

 @RequestMapping(value="/{id}", method={RequestMethod.GET,RequestMethod.POST}) public @ResponseBody BufferedImage getImage(@PathVariable String id) { try { //Modified slightly to protect the innocent return ImageIO.read((new URL(IMAGE_URL + id)).openStream()); } catch (IOException io) { return defaultImage(); } } 

and in my spring context file:

 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="order" value="1" /> <property name="messageConverters"> <list> <!-- Converter for images --> <bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"> <property name="defaultContentType" value="image/png"/> </bean> <!-- This must come after our image converter --> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/> </list> </property> </bean> 

Not sure if this extra layer matters, but I thought it was best to mention it.)

Any ideas / suggestions would be highly appreciated.

Thanks BJ

+4
source share
1 answer

When you use ImageIO.read, you get a BufferedImage object, which is in the internal Java format, not in PNG format. If you write this to a file, you write this internal representation. I'm a little surprised that it is readable at all.

+1
source

All Articles