create Image From Panel - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage Create

Description

create Image From Panel

Demo Code


import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.PixelGrabber;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.apache.log4j.Logger;

public class Main{
    public static BufferedImage createImageFromPanel(JPanel panel, int w,
            int h) {
        JFrame f = new JFrame();
        f.setSize(480, 640);// ww w. j  a va 2s  .co  m
        f.setContentPane(panel);
        f.setVisible(true);
        BufferedImage bi = new BufferedImage(w, h,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bi.createGraphics();
        //g.dispose();
        panel.paint(g);
        g.dispose();
        try {
            TestUtil.saveImageWithNewName(bi, "\\.bmp", "_chart.png");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bi;
    }
}

Related Tutorials