欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java 复制到剪切板

程序员文章站 2022-05-16 09:28:12
...
package com.zzstxx.barcode.utils;

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

/**
 * java 复制到剪切板
 * @author Administrator
 *
 */
public class CutBanUtils {

	/**
	 * 复制String到剪切板
	 * 
	 * @param writeMe
	 */
	protected static void setClipboardText(String writeMe) {
		Clipboard sysc = Toolkit.getDefaultToolkit().getSystemClipboard();
		Transferable tText = new StringSelection(writeMe);
		sysc.setContents(tText, null);
	}

	/**
	 * 赋值图像到剪切板
	 * @param image
	 */
	public static void setClipboardImage(final Image image) {
		Transferable trans = new Transferable() {
			public DataFlavor[] getTransferDataFlavors() {
				return new DataFlavor[] { DataFlavor.imageFlavor };
			}
			public boolean isDataFlavorSupported(DataFlavor flavor) {
				return DataFlavor.imageFlavor.equals(flavor);
			}
			public Object getTransferData(DataFlavor flavor)
					throws UnsupportedFlavorException, IOException {
				if (isDataFlavorSupported(flavor)){
					return image;
				}
				throw new UnsupportedFlavorException(flavor);
			}

		};
		Toolkit.getDefaultToolkit().getSystemClipboard().setContents(trans,
				null);
	}
	
	/**
	 * 读取图片地址,把图片写入图片缓冲区
	 * @param imagePath
	 * @return
	 * @throws IOException
	 */
	public static BufferedImage readImage(String imagePath) throws IOException{
		File f = new File(imagePath);
		BufferedImage bi = ImageIO.read(f);
		return bi;
	}
	
	/**
	 * 方法一:把图片读入缓冲区后复制到剪切板
	 * @param imagePath
	 */
	public static void copyCut(String imagePath){
		BufferedImage image = null;
		try {
			image = CutBanUtils.readImage(imagePath);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    CutBanUtils.setClipboardImage(image);
	}
	
	/**
	 * 方法二:一般图像没问题,如果是二维条码的话,建议使用方法一
	 * @param filePath
	 */
	public static void copyCutByToolkit(String filePath){
		Image image = Toolkit.getDefaultToolkit().getImage(filePath);
		CutBanUtils.setClipboardImage(image);
	}

	public static void main(String[] args) {
		//CutBanUtils.setClipboardText("周旭锋");
		CutBanUtils.copyCutByToolkit("e:/1.jpg");
	    //CutBanUtils.copyCut("e://1.jpg");
	}
}
 

上一篇: vba

下一篇: VueI18n多语言