0

First in my servlet I was using a Image-Servlet jar from some blog, my images were working fine. But the problem was any one can use inspect element and append the url with ../ to get to other directories also which was a big security problem. So I asked a question on SO, people suggested to make my own code as it was easy and I could have full control.

So here is my code,

    String path1=getServletConfig().getServletContext().getRealPath("");      
    System.out.println(path1);  // /usr/share/tomcat7/webapps/myProject    
    String l = File.separator;

    f = new File(path1+l+"images"+l+"load.gif"); 
    BufferedImage bi = ImageIO.read(f);
    OutputStream out = response.getOutputStream();
    ImageIO.write(bi, "gif", out);
    out.close();

It works good, but the problem is the image dont animate any more. I tried downloading it and opened it but it was not animating.

So I guess during reading the file into bufferedImage something changed.

the images looks like these
animating gif non animating gif
You can see in inspect element or source that both are gif but only one is animating

Harry
  • 1,572
  • 2
  • 17
  • 31

1 Answers1

1

You are just sending the first frame of the image.

ImageIO.read reads only the first frame (and a BufferedImage can only contain a single frame/image)

You can achieve it by the same technique used to send any binary content.

 String path1=getServletConfig().getServletContext().getRealPath("");      
 System.out.println(path1);  // /usr/share/tomcat7/webapps/myProject    
 String l = File.separator;

 f = new File(path1+l+"images"+l+"load.gif"); 
 OutputStream out = response.getOutputStream();
 InputStream in = new FileInputStream(f);

 try {
         byte[] buffer = new byte[1024]; 
         int count;

         while ((count = in.read(buffer)) != -1) {
           out.write(buffer, 0, count);
         }

// Flush out stream, to write any remaining buffered data
out.flush();
 }
finally {
in.close(); 
}


 out.close();

credits to this

Community
  • 1
  • 1