Reputation: 105
Considering the code :
Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
DataFlavor[] flavors = cb.getAvailableDataFlavors();
flavors = cb.getAvailableDataFlavors();
for (DataFlavor flavor : flavors) {
System.out.println(flavor);
}
BufferedImage buff = // flavors <- I don't know what to put here to make it working;
File file = new File("newimage.png");
ImageIO.write(buff,"png", file);
Which returns :
java.awt.datatransfer.DataFlavor[mimetype=image/x-java-image;representationclass=java.awt.Image]
How to set the BufferedImage line in order to save this as a picture, (let's say png file)?
Thanks for your help!
Upvotes: 1
Views: 1648
Reputation: 168845
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.imageio.ImageIO;
import java.io.File;
public class SaveClipboardScreenshot {
public static void main(String[] args) throws Exception {
// get the screenshot
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_PRINTSCREEN);
robot.delay(40);
robot.keyRelease(KeyEvent.VK_PRINTSCREEN);
robot.delay(404);
Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
DataFlavor[] flavors = cb.getAvailableDataFlavors();
System.out.println("After: ");
for (DataFlavor flavor : flavors) {
System.out.println(flavor);
if (flavor.toString().indexOf("java.awt.Image")>0) {
Object o = cb.getData(flavor);
Image i = (Image)o;
// ImageIO will not write an Image
// It will write a BufferedImage (a type of RenderedImage)
BufferedImage bi = new BufferedImage(
i.getWidth(null),
i.getHeight(null),
BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
g.drawImage(i, 0, 0, null);
g.dispose();
JScrollPane sp = new JScrollPane(new JLabel(new ImageIcon(bi)));
sp.setPreferredSize(new Dimension(800,600));
JOptionPane.showMessageDialog(null, sp);
File f = new File(
System.getProperty("user.home") +
File.separator +
"the.png");
ImageIO.write(bi, "png", f);
}
}
}
}
How can I use your code into a static function?
In Java they are called methods, and every main
is static.
Ex returning a File.
Change
public static void main(String[] args) throws Exception {
..to something like..
public static File getScreenshot() throws Exception {
..and also change..
ImageIO.write(bi, "png", f);
..to..
ImageIO.write(bi, "png", f);
return f;
Upvotes: 1
Reputation: 50041
try {
Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
BufferedImage img = (BufferedImage)cb.getData(DataFlavor.imageFlavor);
File file = new File("newimage.png");
ImageIO.write(img, "png", file);
} catch (Exception e) { throw new RuntimeException(e); }
Upvotes: 1
Reputation: 8640
did you tried
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
int n=0
for (DataFlavor flavor : flavors) {
BufferedImage image = (BufferedImage)clipboard.getData(flavor);
File file = new File("image"+ n+".png");
ImageIO.write(image , "png", file);
n++;
}
Upvotes: 0