packagecom;importjava.awt.Graphics2D;importjava.awt.Image;importjava.awt.Toolkit;importjava.awt.datatransfer.Clipboard;importjava.awt.datatransfer.DataFlavor;importjava.awt.datatransfer.StringSelection;importjava.awt.datatransfer.Transferable;importjava.awt.datatransfer.UnsupportedFlavorException;importjava.awt.image.BufferedImage;importjava.awt.image.RenderedImage;importjava.io.File;importjava.io.IOException;importjavax.imageio.ImageIO;public classTest {public static voidmain(String[] args) {try{//获取粘贴板图片
Image image =Test.getImageFromClipboard();
File file= new File("D:\\a.png");//转成jpg//BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);//转成png
BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Graphics2D g=bufferedImage.createGraphics();
g.drawImage(image,null, null);//ImageIO.write((RenderedImage)bufferedImage, "jpg", file);
ImageIO.write((RenderedImage)bufferedImage, "png", file);
}catch(Exception e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}/*** 从剪切板获得文字。*/
public staticString getSysClipboardText() {
String ret= "";
Clipboard sysClip=Toolkit.getDefaultToolkit().getSystemClipboard();//获取剪切板中的内容
Transferable clipTf = sysClip.getContents(null);if (clipTf != null) {//检查内容是否是文本类型
if(clipTf.isDataFlavorSupported(DataFlavor.stringFlavor)) {try{
ret=(String) clipTf
.getTransferData(DataFlavor.stringFlavor);
}catch(Exception e) {
e.printStackTrace();
}
}
}returnret;
}/*** 将字符串复制到剪切板。*/
public static voidsetSysClipboardText(String writeMe) {
Clipboard clip=Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable tText= newStringSelection(writeMe);
clip.setContents(tText,null);
}/*** 从剪切板获得图片。*/
public static Image getImageFromClipboard() throwsException {
Clipboard sysc=Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable cc= sysc.getContents(null);if (cc == null)return null;else if(cc.isDataFlavorSupported(DataFlavor.imageFlavor))return(Image) cc.getTransferData(DataFlavor.imageFlavor);return null;
}/*** 复制图片到剪切板。*/
public static void setClipboardImage(finalImage image) {
Transferable trans= newTransferable() {publicDataFlavor[] getTransferDataFlavors() {return newDataFlavor[] { DataFlavor.imageFlavor };
}public booleanisDataFlavorSupported(DataFlavor flavor) {returnDataFlavor.imageFlavor.equals(flavor);
}publicObject getTransferData(DataFlavor flavor)throwsUnsupportedFlavorException, IOException {if(isDataFlavorSupported(flavor))returnimage;throw newUnsupportedFlavorException(flavor);
}
};
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(trans,null);
}
}