Jump to content

Check out our Community Blogs

Register and join over 40,000 other developers!

Recent Status Updates

View All Updates

- - - - -

Java copy image from Clipboard


  • Please log in to reply
No replies to this topic

#1 farrell2k


    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 169 posts

Posted 07 August 2010 - 10:36 PM

This is a simple tutorial showing you how to copy image data from your system clipboard and save it as a file on disk.

The first thing you want to do is open an image somewhere and copy it to memory, or you could just tap the print screen key on your keyboard.

Next we need to create a clipboard object.

Then we simply call getData() from our clipBoard, specifying the "flavor" of the data that the clipboard contains. In this case it is Image Data. We use the getData method to create a BufferedImage.

We handle all necessary exceptions, then we create a file and use ImageIO.write() to write the image data to the file, then to disk.

Here's the code:

 * @author tom
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class Main {

     * @param args the command line arguments
    public static void main(String[] args) {
        //create clipboard object
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        try {
            //Get data from clipboard and assign it to an image.
            //clipboard.getData() returns an object, so we need to cast it to a BufferdImage.
            BufferedImage image = (BufferedImage)clipboard.getData(DataFlavor.imageFlavor);
            //file that we'll save to disk.
            File file = new File("image.jpg");
            //class to write image to disk.  You specify the image to be saved, its type,
            // and then the file in which to write the image data.
            ImageIO.write(image, "jpg", file);
        //getData throws this.
        catch(UnsupportedFlavorException ufe) {
        catch(IOException ioe) {

The clipboard class also supports text. For more details, check out the Clipboard class.
  • 0

Also tagged with one or more of these keywords: java

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download