I have a JPanel showing lots of random images on it.
I would like to have user to save the entire JPanel to a JPEG format.
How can I do that?
BufferedImage image = new BufferedImage(jpanel.getWidth(),
jpanel.getHeight(),BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = image.createGraphics();
jpanel.paint(g2);
javax.imageio.ImageIO.write(image, "jpeg", new
java.io.File("file.jpeg"));
> I have a JPanel showing lots of random images on it.
> I would like to have user to save the entire JPanel to a JPEG format.
> How can I do that?
import javax.swing.*;
import javax.imageio.*;
import java.awt.image.*;
import java.awt.*;
import java.io.*;
public class ComponentToImageFile{
JFrame frame;
JLabel label;
JButton button;
public ComponentToImageFile(){
frame = new JFrame("ComponentToImageFile");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel(new ImageIcon("siggy.jpg"));
button = new JButton("We Love Siggy");
Container con = frame.getContentPane();
con.add(label, BorderLayout.CENTER);
con.add(button, BorderLayout.SOUTH);
frame.setBounds(0, 0, 300, 200);
frame.setVisible(true);
}
public void writeFile(Component comp, String fileName){
String ext;
String[] temp = fileName.split("\\.");
ext = temp[temp.length - 1];
// RenderedImage rImage = comp2Image(comp);
RenderedImage rImage = getCompImageFromRobot(comp);
try{
File file = new File(fileName);
if (ext.equals("png")){
ImageIO.write(rImage, "png", file);
}
else if (ext.equals("jpg")){
ImageIO.write(rImage, "jpg", file);
}
else{
System.err.println("Unsupported format: " + ext);
}
}
catch(IOException e){
e.printStackTrace();
}
}
RenderedImage getCompImageFromRobot(Component comp){
int x, y, width, height;
BufferedImage bImage = null;
//these conditionals are necessary, but I don't know why
if (comp instanceof Window){
x = comp.getX();
y = comp.getY();
}
else{
Point p = comp.getLocationOnScreen();
x = p.x;
y = p.y;
}
width = comp.getWidth();
height = comp.getHeight();
Rectangle rec = new Rectangle(x, y, width, height);
try{
Robot robo = new Robot();
//you need to give generous amount of delay
robo.delay(100);
bImage = robo.createScreenCapture(rec);
}
catch(Exception e){
e.printStackTrace();
}
return bImage;
}
RenderedImage comp2Image(Component cmp){
int width, height;
width = cmp.getWidth();
height = cmp.getHeight();
BufferedImage bImage
= new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bImage.createGraphics();
cmp.paint(g2d);
g2d.dispose();
return bImage;
}
public static void main(String[] args){
ComponentToImageFile ctif = new ComponentToImageFile();
ctif.writeFile(ctif.frame, "SiggyFrame.png");
ctif.writeFile(ctif.button, "SiggyButton.png");
}
}