2012-02-25 28 views
1

我正在使用Applet从剪贴板保存图像。图像被保存,但其格式发生了一些变化。它变暗,失去了颜色。使用小应用程序从Mac OSX上的剪贴板抓取图像

这里就是我正在做它:

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,得到了更糟的结果:黑色图像

回答

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); 
} 
+0

当您尝试访问系统剪贴板时,请注意这只能用于JDK 1.6。截至2013年10月6日,JDK 1.7中存在一个错误:http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=8019465 – 2013-10-05 11:33:18

0

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

+0

我试过了。取而代之的是黑色的png。 – 2012-02-25 15:58:50

相关问题