利用QRCode生成二维码

在群聊天里面看到有人要QRCode.jar,在网上一查才知道是生成和解析二维码的包。在网上找了一下用法,很好用。在此贴出来。

QRCode.jar 免积分下载地址:http://download.csdn.net/detail/levelmini/7470979 

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import jp.sourceforge.qrcode.QRCodeDecoder;
import jp.sourceforge.qrcode.data.QRCodeImage;
import jp.sourceforge.qrcode.exception.DecodingFailedException;

import com.swetake.util.Qrcode;
/**
 * 
 * 二维码生成器
 * 
 * @blog http://sjsky.iteye.com
 * 
 * @author Michael
 */

public class TestQRCode {
	//设置二维码中间图片的宽高
	private int imageWidth = 30;
	private int imageHeight = 30;
	/**
	 * 生成二维码(QRCode)图片
	 * @param content 二维码索表示的内容。
	 * @param imgPath 二维码图片存放路径。
	 * @param centerImgPath 二维码中央的logo。可以为空字符串或null
	 */

	public void encoderQRCode(String content, String imgPath ,String centerImgPath) {
		try {
			Qrcode qrcodeHandler = new Qrcode();
			qrcodeHandler.setQrcodeErrorCorrect('M');
			qrcodeHandler.setQrcodeEncodeMode('B');
			qrcodeHandler.setQrcodeVersion(7);
			System.out.println(content);
			byte[] contentBytes = content.getBytes("gb2312");
			BufferedImage bufImg = new BufferedImage(140, 140,
			BufferedImage.TYPE_INT_RGB);
			Graphics2D gs = bufImg.createGraphics();
			gs.setBackground(Color.WHITE);
			gs.clearRect(0, 0, 140, 140);
			// 设定图像颜色> BLACK
			gs.setColor(Color.BLACK);
			// 设置偏移量 不设置可能导致解析出错
			int pixoff = 2;
			// 输出内容> 二维码
			if (contentBytes.length > 0 && contentBytes.length < 120) {
				boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes);
				for (int i = 0; i < codeOut.length; i++) {
					for (int j = 0; j < codeOut.length; j++) {
						if (codeOut[j][i]) {
							gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
						}
					}
				}
			} else {
				System.err.println("QRCode content bytes length = "
				+ contentBytes.length + " not in [ 0,120 ]. ");
			}
			if (!("".equals(centerImgPath) || null == centerImgPath)) {
				createPhotoAtCenter(bufImg,centerImgPath);				
			}
			gs.dispose();
			bufImg.flush();
			
			File imgFile = new File(imgPath);
			// 生成二维码QRCode图片
			ImageIO.write(bufImg, "png", imgFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
     * 解码二维码,如果中间带有logo则解析可能出乱码。
     * @param imgPath
     * @return String
     */ 
    public String decoderQRCode(String imgPath) { 
        // QRCode 二维码图片的文件 
        File imageFile = new File(imgPath); 
        BufferedImage bufImg = null; 
        String decodedData = null; 
        try { 
            bufImg = ImageIO.read(imageFile); 
            QRCodeDecoder decoder = new QRCodeDecoder(); 
            decodedData = new String(decoder.decode(new J2SEImage(bufImg))); 
        } catch (IOException e) { 
            System.out.println("Error: " + e.getMessage()); 
            e.printStackTrace(); 
        } catch (DecodingFailedException dfe) { 
            System.out.println("Error: " + dfe.getMessage()); 
            dfe.printStackTrace(); 
        } 
        return decodedData; 
    } 
    
    class J2SEImage implements QRCodeImage { 
        BufferedImage bufImg; 
        public J2SEImage(BufferedImage bufImg) { 
            this.bufImg = bufImg; 
        } 
        public int getWidth() { 
            return bufImg.getWidth(); 
        } 
        public int getHeight() { 
            return bufImg.getHeight(); 
        } 
        public int getPixel(int x, int y) { 
            return bufImg.getRGB(x, y); 
        } 
    } 
    
    /**
     * 在二维码中间加入图片
     * 
     * @param bugImg
     * @return
     */
    private BufferedImage createPhotoAtCenter(BufferedImage bufImg ,String centerImgPath) throws Exception {
    	 Image im = ImageIO.read(new File(centerImgPath));
         Graphics2D g = bufImg.createGraphics();
         //获取bufImg的中间位置
         int centerX = bufImg.getMinX() + bufImg.getWidth()/2 - imageWidth/2;
         int centerY = bufImg.getMinY() + bufImg.getHeight()/2 - imageHeight/2;
         g.drawImage(im,centerX,centerY,imageWidth,imageHeight,null);
         g.dispose();
         bufImg.flush();
    	return bufImg;
    }

	public static void main(String[] args) {
		//生成二维码
		String imgPath = "D:/QRcode.png";
		String content = "http://blog.csdn.net/levelmini";
		TestQRCode handler = new TestQRCode();
		handler.encoderQRCode(content, imgPath,"d:/levelmini.png");
		System.out.println("encoder QRcode success");
		//解析二维码文件
        String imgPath1 = "D:/QRcode.png"; 
        String decoderContent = handler.decoderQRCode(imgPath1); 
        System.out.println("解析结果如下:"); 
        System.out.println(decoderContent); 
        System.out.println("========decoder success!!!");
	}
}
效果:

利用QRCode生成二维码_第1张图片

你可能感兴趣的:(JAVA)