Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
366 views
in Technique[技术] by (71.8m points)

java - How to replace com.sun.image.codec.jpeg.JPEGImageEncoder in this code?

I have used com.sun.image.codec.jpeg.JPEGImageEncoder to handle JPEG images, like charts and others, in my webapp. Now, I am updating my machine to use JDK7, but this version deprecated this class. Below is the code that I need to change:

public void processChart(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    response.setContentType("image/jpeg");
    out = response.getOutputStream();
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires",0);
    try {
        int w = Integer.parseInt(request.getParameter("WIDTH"));
        int h = Integer.parseInt(request.getParameter("HEIGHT"));
        java.awt.image.BufferedImage ChartImage = new java.awt.image.BufferedImage(w,h,java.awt.image.BufferedImage.TYPE_INT_RGB);
        java.awt.Graphics2D ChartGraphics = ChartImage.createGraphics();
        Chart c = getChart(request);
        c.setSize(w,h);
        c.paint(ChartGraphics);
        // CODE BELOW TO CHANGE...
        com.sun.image.codec.jpeg.JPEGImageEncoder encoder = 
                                 com.sun.image.codec.jpeg.JPEGCodec.createJPEGEncoder(out);
        encoder.encode(ChartImage);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private Chart getChart(HttpServletRequest request) {
    chartLoader loader = new chartLoader(null);
    loader.paintDirect = true;
    java.util.Enumeration ps = request.getParameterNames();
    while (ps.hasMoreElements()) {
        String name = (String) ps.nextElement();
        loader.setParameter(name,request.getParameter(name));
    }
    // create Chart
    Chart chart = loader.build(false,false);
    Chart.tmpImage = new java.awt.image.BufferedImage(200,200,java.awt.image.BufferedImage.TYPE_INT_RGB);
    return chart;
}
question from:https://stackoverflow.com/questions/8015291/how-to-replace-com-sun-image-codec-jpeg-jpegimageencoder-in-this-code

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use ImageIO, it can read/write JPEG, PNG, GIF, and BMP out of the box.

ImageIO.write(ChartImage, "jpeg", out);

Usually the static write(...) and read(...) methods are enough, if you need to control compression or handle image meta data, check out the Java Image I/O API Guide.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...