java 生成二维码

我利用的是QRCode.jar和Qrcode_swetake.jar做的

jar都在这里jar

主函数类:

import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

public class Test {

	public static void main(String[] args) {
		
		QRCodeEncoderHandler header=new QRCodeEncoderHandler();
		String imgPath = "D:/test/111.png"; 
		String content = "12345";
		
			try {
				 BufferedImage bufImg=header.encoderQRCode(content, imgPath);
				 File file=new File(imgPath);
				 ImageIO.write(bufImg, "png", file); 
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		System.out.println("OK");
	}
}

工具类:

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

import com.swetake.util.Qrcode;

public class QRCodeEncoderHandler {
	 public BufferedImage encoderQRCode(String content, String imgPath) throws Exception  {
		 BufferedImage bufImg = null; 
		 Qrcode qrcodeHandler = new Qrcode();  
		 qrcodeHandler.setQrcodeEncodeMode('M');
		 qrcodeHandler.setQrcodeEncodeMode('B');
		 qrcodeHandler.setQrcodeVersion(7);
		 byte[] contentBytes = content.getBytes("utf-8"); 
		 int imgSize = 140; 
		 bufImg= new BufferedImage(imgSize, imgSize, BufferedImage.TYPE_INT_RGB);
		 Graphics2D gs = bufImg.createGraphics(); 
		 gs.setBackground(Color.WHITE);  
         gs.clearRect(0, 0, imgSize, imgSize); 
         gs.setColor(Color.BLACK);  
         //设置偏移量,不设置可能导致解析出错  
         int pixoff = 2; 
         if (contentBytes.length > 0 && contentBytes.length < 800) {  
             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{
        	 throw new Exception("QRCode content bytes length = " + contentBytes.length + " not in [0, 800]."); 
         }
         gs.dispose();  
         bufImg.flush();
         return bufImg; 
	 }
	  
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值