Obtains a BufferedImage from the clipboard. - Java Native OS

Java examples for Native OS:Clipboard

Description

Obtains a BufferedImage from the clipboard.

Demo Code

/*/*  ww w  .  j a v a  2  s.c  o  m*/
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
//package com.java2s;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;

import java.awt.image.BufferedImage;

public class Main {
    public static void main(String[] argv) throws Exception {
        System.out.println(pasteImageFromClipboard());
    }

    /**
     * Obtains a BufferedImage from the clipboard.
     *
     * @return      the obtained image, null if not available
     * @see      BufferedImage#TYPE_INT_RGB
     */
    public static BufferedImage pasteImageFromClipboard() {
        java.awt.image.BufferedImage result;
        Image img;
        int width;
        int height;
        Graphics g;

        result = null;
        img = (Image) pasteFromClipboard(DataFlavor.imageFlavor);
        if (img != null) {
            width = img.getWidth(null);
            height = img.getHeight(null);
            result = new java.awt.image.BufferedImage(width, height,
                    java.awt.image.BufferedImage.TYPE_INT_RGB);
            g = result.createGraphics();
            g.drawImage(img, 0, 0, null);
            g.dispose();
        }

        return result;
    }

    /**
     * Obtains an object from the clipboard.
     *
     * @param flavor   the type of object to obtain
     * @return      the obtained object, null if not available
     */
    public static Object pasteFromClipboard(DataFlavor flavor) {
        Clipboard clipboard;
        Object result;
        Transferable content;

        result = null;

        try {
            clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
            content = clipboard.getContents(null);
            if ((content != null)
                    && (content.isDataFlavorSupported(flavor)))
                result = content.getTransferData(flavor);
        } catch (Exception e) {
            result = null;
        }

        return result;
    }
}

Related Tutorials