利用QrCode生成二维码

文章主要用QrCodejar包来生成二维码,用扫一扫即可扫出来对应的二维码:

准备对应Q人Codejar包

package com.allen.test;

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

import javax.imageio.ImageIO;

import com.swetake.util.Qrcode;

public class QrCodeAllenTest {

	public static void getQrCodeByImage(String contents,String path){
		int width =140;
		int height = 140;
		try {
			Qrcode qrCode = new Qrcode();
			//设置出错率
			qrCode.setQrcodeErrorCorrect('M');
			qrCode.setQrcodeEncodeMode('B');
			//二维码尺寸(1-40)
			qrCode.setQrcodeVersion(7);
			//设置尺寸
			BufferedImage bufImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
			//绘制二维码图片
			Graphics2D gs = bufImg.createGraphics();
			//设置二维码的背景颜色:白色
			gs.setBackground(Color.white);
			//创建图片的矩形区域
			gs.clearRect(0, 0, width, height);
			//设置二维码的颜色
			gs.setColor(Color.green);
			
			//获取内容,通过数组形式,设置编码格式
		
			byte[] contentByte = contents.getBytes("gb2312");
			
			//设置偏移量(不设置可能会导致解析错误)
			int pixOff = 2;
			
			//输出二维码:插件最大只能存储120个字符
			if(contentByte.length>0 && contentByte.length<120){
				//把一维数组中的值放到一个boolean类型的数组中
				boolean [][]codeOut = qrCode.calQrcode(contentByte);
				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.out.println("解析出错了!!!!,内容长度超出最大的限制");
			}
			gs.dispose();
			bufImg.flush();
			//生成二维码图片
			File imgFile = new File(path);
			ImageIO.write(bufImg, "png", imgFile);
			System.out.println("二维码生成成功!!!");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public  static void main(String[] args){
		System.out.println("哈哈");
		String contents = "<h1>你好!JAVA!QrCode</h1>";
		String path = "G://ewm//";
		QrCodeAllenTest.getQrCodeByImage(contents, path);
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章