This week's book giveaway is in the Java in General forum.
We're giving away four copies of Think Java: How to Think Like a Computer Scientist and have Allen B. Downey & Chris Mayfield on-line!
See this thread for details.
Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Swing to Image conversion

 
Vani Shastri
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

I am new to this topic of converting swing into an image.

1. Why should we convert a swing into an image?
2. How to implement the same?

Thank you.
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
not sure exactly what you're asking, but the easiest way to display an image
in swing is to use a JLabel and it's icon property

JLabel label = new JLabel(new ImageIcon("test.gif"));
 
Vani Shastri
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Micheal,

My doubt was- how to save a JFrame as a jpeg/gif image?

Thanks
 
Vani Shastri
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi once again,

finally i found it :

BufferedImage image = new BufferedImage(w, h,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = image.createGraphics();
comp.paint(g2);
g2.dispose();
ImageIO.write(image, "jpeg", new File("example.jpeg"));

Thanks for the help offered.
 
Vani Shastri
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
another doubt



The destination of jpeg image that is created is by default where its class file is present.
How to save the jpeg at the required destination ( i dont want to mention the path in the class)? just the same way how we get the dialog box when we save any other file.
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
use a JFileChooser's showSaveDialog()
 
Vani Shastri
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Michael,

Yeah it worked !!! Thanks.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic