0

This is my first servlet to generate and display image to the client,

But There is compile time error in the mentioned section by commect.

public class DynamicImage extends HttpServlet {

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

    response.setContentType("image/jpeg");

    //create image
    int width = 200;
    int height = 30;
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

    //get drawing context
    Graphics2D g = (Graphics2D) image.getGraphics();
    g.setColor(Color.GRAY);
    g.fillRect(0, 0, width, height);

    //draw a string
    g.setColor(Color.WHITE);
    g.setFont(new Font("Dialog", Font.PLAIN, 14));
    g.drawString("My String!", 10, height / 2 + 4);

    //draw a border
    g.setColor(Color.BLACK);
    g.drawRect(0, 0, width - 1, height - 1);

    //dispose context
    g.dispose();

    //send back image to the client
    ServletOutputStream sos = response.getOutputStream();
    com.sun.image.codec.jpeg.JPEGImageEncoder encoder = JPEGCodec // Compile Time Error, cant find JPEGCodec

    }
}

My IDE (Netbeans) cant find and import JPEGCodec , What is the solution?

  • 4
    classes from the com.sun package are not documented, and not supposed to be used. Use a public API that can write images in JPEG, like ImageIO. – JB Nizet Nov 25 '14 at 18:19
  • Highly advise against generating images in servlets. The image should already exist on the file system or in a database; not only is it inefficient to do this in the servlet, but some servers do not have graphics cards or a GraphicsEnvironment, so your graphics operations may fail. – ControlAltDel Nov 25 '14 at 18:25
  • @ControlAltDel I can think of quite a few use cases for generating images server side. Producing images server-side isn't unusual at all. To handle not have a graphics system just set the property for headless mode: -Djava.awt.headless=true – Michael Nov 25 '14 at 20:09

2 Answers2

0

Take a look at this answer

I would recommend not to use this class. It's nothing but headache.

Community
  • 1
  • 1
deepakborania
  • 166
  • 2
  • 8
0

You are needed to download rt.jar file and add it in your class path.
Download it from here.
If above link does not work visit here

afzalex
  • 8,598
  • 2
  • 34
  • 61