Jump to content




Recent Status Updates

  • Photo
      30 Sep
    rhossis

    laptop hard disk seated beneath motherboard but with no access panel. 7 hours to replace :(

    Show comments (3)
  • Photo
      19 Sep
    Chall

    I love it when you go to write a help thread, then while writing, you reach an enlightenment, and figure it out yourself.

    Show comments (3)
View All Updates

Developed by Kemal Taskin
Photo
- - - - -

Java copy image from Clipboard

java

  • Please log in to reply
No replies to this topic

#1 farrell2k

farrell2k

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 157 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) {
            ufe.printStackTrace();
        }
        
        catch(IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

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