我正在使用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,但结果更糟:黑色图片
最佳答案
为了解决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);
}
关于java - 使用小程序从Mac OSX上的剪贴板中抓取图像,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9443691/