我正在使用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上的问题,我使用了在使用Java从Mac OS X剪贴板获取图像的噩梦中提出的解决方案。
我将检索到的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);
}
PNG是Mac电脑的首选图像格式。您可能想尝试保存为那样,然后在需要时转换为JPG。