Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Servlet displaying an image

 
Anthony Smith
Ranch Hand
Posts: 285
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to use my servlet as the src for an <img> tag in a jsp page. That servlet should display a picture, that is not located in the webapp.
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The short answer is that you need to get a java.awt.Image and a java.awt.Graphics context to draw on it, then get a separate package to convert it into the image type of choice.
I use the com.sun.image.codec.jpeg.* package that comes with Java, but it's unsupported and generally not recommended. You'd be able to find others out there.
The slightly longer answer is:

Dave
 
Anthony Smith
Ranch Hand
Posts: 285
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your help.
Along with this website and your help
http://developpeur.journaldunet.com/ressource/java/ja_effets_jpeggenerator.shtml
I can do a servlet called by an <IMG SRC> tag, but it shows a pic (Black box), but now I dont know how to use my own image calling the BufferedImage img or Image img class in java.
 
Anthony Smith
Ranch Hand
Posts: 285
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, I got it to work, but what about with GIFs?
 
Justin Chu
Ranch Hand
Posts: 209
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
// FOR GIF, change content type accordingly. I'm not sure what's the content type of GIF files.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ImageLoader extends HttpServlet{
public ImageLoader() {}
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
res.setContentType("image/jpeg");
File image = new File("/home/chu/image01.jpg");
FileInputStream fis = new FileInputStream(image);
OutputStream out = res.getOutputStream();
DataOutputStream ds = new DataOutputStream(out);
byte b[] = new byte [32*1024];
while (fis.read(b) != -1){
ds.write(b);
}
}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic