使用applet从Mac OSX上的剪贴板中抓取图像

时间:2012-02-25 11:46:07

标签: java macos applet

我正在使用Applet从剪贴板保存图像。图像已保存,但其格式出现了问题。它变暗了,颜色变暗了。

这是我如何做的:

AccessController.doPrivileged(new PrivilegedAction() {
    public Object run() {

        try {
            //create clipboard object
            Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
            //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("/tmp/clipboard.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();
            return "Não tem imagem na área de transferência";
        } catch (Exception ioe){
            ioe.printStackTrace();
        }
        return null;
    }
}

);

我读到Mac使用不同的图像格式,但我没有找到如何将其转换为我可以保存的格式。我想象java应该照顾它。

那么,如何将图像从剪贴板转换为jpg?

PS。我尝试使用png而不是jpg,得到了更糟糕的结果:黑色图像

2 个答案:

答案 0 :(得分:0)

PNG是Mac的首选图像格式。您可能希望尝试保存,然后在需要之后转换为JPG。

答案 1 :(得分:0)

要解决Mac上的问题,我使用了The nightmares of getting images from the Mac OS X clipboard using Java上提出的解决方案。

我将检索到的BufferedImage传递给将其重绘为新的BufferedImage的方法,返回一个有效的图像。以下是该页面的代码:

public static BufferedImage getBufferedImage(Image img) {
        if (img == null) return null;
        int w = img.getWidth(null);
        int h = img.getHeight(null);
        // draw original image to thumbnail image object and
        // scale it to the new size on-the-fly
        BufferedImage bufimg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = bufimg.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2.drawImage(img, 0, 0, w, h, null);
        g2.dispose();
        return bufimg;
    }

以及我如何使用它:

Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
//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);

if (isMac()) {
    image = getBufferedImage(image);
}