java swing从剪切板黏贴图片
代码:
public static BufferedImage getClipboardImage(Frame frame) {
// java.lang.ClassCastException: sun.awt.datatransfer.TransferableProxy cannot be cast to sun.awt.datatransfer.ClipboardTransferable
Transferable trans=frame.getToolkit().getSystemClipboard().getContents(null);
BufferedImage image=null;
try {
if (null != trans && trans.isDataFlavorSupported(DataFlavor.imageFlavor)) {
Object obj22=trans.getTransferData(DataFlavor.imageFlavor);
if(!ValueWidget.isNullOrEmpty(obj22)){
if(obj22 instanceof BufferedImage){
image = (BufferedImage) obj22;
} else if (obj22 instanceof sun.awt.image.MultiResolutionCachedImage) {//兼容mac os
sun.awt.image.MultiResolutionCachedImage cachedImage = (sun.awt.image.MultiResolutionCachedImage) obj22;
if (null == cachedImage) {
return null;
}
sun.awt.image.ToolkitImage toolkitImage = (sun.awt.image.ToolkitImage) cachedImage.getScaledInstance(cachedImage.getWidth(null), cachedImage.getHeight(null), Image.SCALE_SMOOTH);
if (null == toolkitImage) {
return null;
}
java.awt.image.FilteredImageSource filteredImageSource = (java.awt.image.FilteredImageSource) ReflectHWUtils.getObjectValue(toolkitImage, "source");
if (null == filteredImageSource) {
return null;
}
sun.awt.image.OffScreenImageSource imageSource = (sun.awt.image.OffScreenImageSource) ReflectHWUtils.getObjectValue(filteredImageSource, "src");
image = (BufferedImage) ReflectHWUtils.getObjectValue(imageSource, "image");
// System.out.println(imageSource);
}
}
}
} catch (UnsupportedFlavorException e1) {
e1.printStackTrace();
GUIUtil23.errorDialog(e1);
} catch (IOException e1) {
e1.printStackTrace();
GUIUtil23.errorDialog(e1);
}
// }
catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return image;
}
调用:
/***
* 把系统剪切板中的图片黏贴到swing的Label控件中
*/
public void pasteClipboardImageAction(){
BufferedImage bufferedimage=ComponentUtil.getClipboardImage(this.frame);
if(ValueWidget.isNullOrEmpty(bufferedimage)){
GUIUtil23.alert("系统剪切板中无图片,请先复制图片");
return;
}
image=bufferedimage;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {//把粘贴过来的图片转为为二进制(字节数组)
ImageIO.write(bufferedimage, read_qrcode_from_pic_format/*jpg*/, baos);
QRbytes= baos.toByteArray();
ComponentUtil.appendResult(resultArea, "粘贴的二维码大小:\t"+QRbytes.length, true);
} catch (IOException e) {
e.printStackTrace();
}
qrResultLabel.setIcon(new ImageIcon(image));
}