首页>代码>Java swing字符串二维码生成器>/QRC/src/com/QRCodeUtil.java
package com;



import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;

import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.filechooser.FileNameExtensionFilter;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

/**
 * 二维码工具类 
 */
public class QRCodeUtil {
	
	private static JFileChooser filechooser = new JFileChooser();
	private static BufferedImage image;
	private static File out = new File("new.jpg");
	private static final String CHARSET = "utf-8";
	private static final String FORMAT_NAME = "JPG";
	private static final int QRCODE_SIZE = 200;// 二维码尺寸
	private static final int WIDTH = 60;// LOGO宽度
	private static final int HEIGHT = 60;// LOGO高度

	private static BufferedImage createImage(String content, String imgPath,
			boolean needCompress) throws Exception {
		Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
		hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
		hints.put(EncodeHintType.MARGIN, 1);
		BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
				BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
		int width = bitMatrix.getWidth();
		int height = bitMatrix.getHeight();
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000
						: 0xFFFFFFFF);
			}
		}
		if (imgPath == null || "".equals(imgPath)) {
			return image;
		}
		// 插入图片
		QRCodeUtil.insertImage(image, imgPath, needCompress);
		return image;
	}

	/**
	 * 插入LOGO
	 * @param source 二维码图片
	 * @param imgPath LOGO图片地址
	 * @param needCompress  是否压缩
	 * @throws Exception
	 */
	private static void insertImage(BufferedImage source, String imgPath,
			boolean needCompress) throws Exception {
		File file = new File(imgPath);
		if (!file.exists()) {
			return;
		}
		Image src = ImageIO.read(new File(imgPath));
		int width = src.getWidth(null);
		int height = src.getHeight(null);
		if (needCompress) { // 压缩LOGO
			if (width > WIDTH) {
				width = WIDTH;
			}
			if (height > HEIGHT) {
				height = HEIGHT;
			}
			Image image = src.getScaledInstance(width, height,
					Image.SCALE_SMOOTH);
			BufferedImage tag = new BufferedImage(width, height,
					BufferedImage.TYPE_INT_RGB);
			Graphics g = tag.getGraphics();
			g.drawImage(image, 0, 0, null); // 绘制缩小后的图
			g.dispose();
			src = image;
		}
		// 插入LOGO
		Graphics2D graph = source.createGraphics();
		int x = (QRCODE_SIZE - width) / 2;
		int y = (QRCODE_SIZE - height) / 2;
		graph.drawImage(src, x, y, width, height, null);
		Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
		graph.setStroke(new BasicStroke(3f));
		graph.draw(shape);
		graph.dispose();
	}

	/**
	 * 生成二维码(内嵌LOGO)
	 * @param content 内容
	 * @param imgPath LOGO地址
	 * @param needCompress 是否压缩LOGO
	 * @param panel 放入的面板          
	 * @throws Exception
	 */
	public static void encode1(String content, String imgPath, 
			boolean needCompress,JPanel panel) throws Exception {
		BufferedImage image = QRCodeUtil.createImage(content, imgPath,
				needCompress);
		ImageIO.write(image, FORMAT_NAME, new File("new.jpg"));
		
		hq(panel);
	}

	/**图片当做面板背景投放*/
	private static void hq(JPanel panel) {
		// TODO Auto-generated method stub
		try {
			image = ImageIO.read(out);
			BackgroundPanel b = new BackgroundPanel(image);
			panel.removeAll();
			panel.add(b);
			panel.repaint();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		out.delete();
	}


	/**
	 * 生成二维码
	 * @param content 内容
	 * @throws Exception
	 */
	public static void encode(String content,JPanel panel) throws Exception {
		QRCodeUtil.encode1(content, content, false, panel);
	}


	/**
	 * 解析二维码
	 * @param file 二维码图片
	 * @throws Exception
	 * @return
	 */
	public static String decode(File file) throws Exception {
		BufferedImage image;
		image = ImageIO.read(file);
		if (image == null) {
			return null;
		}
		BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(
				image);
		BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
		Result result;
		Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
		hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
		result = new MultiFormatReader().decode(bitmap, hints);
		String resultStr = result.getText();
		return resultStr;
	}

	/**
	 * 解析二维码
	 * @param path 二维码图片地址
	 * @throws Exception
	 * @return
	 */
	public static String decode(String path) throws Exception {
		return QRCodeUtil.decode(new File(path));
	}
	
	
	/**保存二维码*/
	public static void Save(){
		if(image == null)
			JOptionPane.showMessageDialog(null, "没有二维码!","提醒",JOptionPane.ERROR_MESSAGE);
		else{
			filechooser.setFileFilter(new FileNameExtensionFilter("jpg/png", new String[] { "jpg","png"}));
			filechooser.setCurrentDirectory(new File("D:\\"));
			filechooser.setDialogTitle("保存图片");
			int i = filechooser.showSaveDialog(null);
			if(i == 0){
				File file = null;
				String filename = filechooser.getSelectedFile().getName();
				if(filename.substring(filename.length() - 1, filename.length()).equals(".")){
					file = new File(filechooser.getSelectedFile()+".jpg");
				}else{
					if(filename.indexOf(".jpg") < 0 && filename.indexOf(".png") < 0 && filename.indexOf(".") < 0)
						file = new File(filechooser.getSelectedFile()+".jpg");
					else
						file = new File(filechooser.getSelectedFile()+"");
				}
				try {
					ImageIO.write(image, "jpg", file);
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		}
	}
}
最近下载更多
luo110012  LV9 2023年5月17日
尹恒yingying  LV18 2021年10月31日
sdasdsad  LV1 2021年9月26日
sky_hui  LV6 2021年8月13日
wyx065747  LV67 2021年7月9日
13043860zj  LV16 2021年6月21日
yiangeee  LV9 2021年1月14日
jweblogic  LV1 2020年10月29日
498215790  LV1 2020年6月3日
IraqiHa  LV6 2020年5月1日
最近浏览更多
GANBINWEI 1月10日
暂无贡献等级
daunjianhui  LV1 2024年12月3日
暂无贡献等级
luo110012  LV9 2023年5月17日
啦啦啦7719  LV15 2023年5月15日
haoyifan 2023年3月23日
暂无贡献等级
暂无贡献等级
微信网友_5992582549164032  LV6 2023年2月16日
mthouse 2022年11月25日
暂无贡献等级
flygrass  LV12 2022年9月16日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友