二维码生成


生成后的图片:

 


所须jre包:Qrcode_swetake.jar  网上均可下载

源代码如下:

package com.yfly.test;

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 java.io.UnsupportedEncodingException;

import javax.imageio.ImageIO;

import com.swetake.util.Qrcode;
/**
 * 二维码生成
 * @author yfly
 *
 */
public class QrcodeImg {
	
	/**
	 * 生成二维码的方法
	 * @param content 二维码内容
	 * @param imgPath 图片路径
	 */
	public static void getQrcodeImg(String content, String imgPath) {
		int width = 235;
		int height = 235;
		//实例化一个Qrcode对象
		Qrcode myQrcode = new Qrcode();
		//设置排错率
		myQrcode.setQrcodeErrorCorrect('M');
		//设置编码方式
		myQrcode.setQrcodeEncodeMode('B');
		//设置二维码版本
		myQrcode.setQrcodeVersion(15);
		
		//绘制二维码-->创建画板
		BufferedImage bfImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		//绘制工具
		Graphics2D gd =bfImg.createGraphics();
		//设置背景色
		gd.setBackground(Color.black);
		//设置前景色
		gd.setColor(Color.white);
		//创建二维码区域
		gd.setClip(0, 0, width, height);
		
		try {
			//处理二维码
			byte[] codeOut = content.getBytes("utf-8");
			boolean[][] code = myQrcode.calQrcode(codeOut);
			for (int i = 0; i < code.length; i++) {
				for (int j = 0; j < code.length; j++) {
					if(!code[j][i]) {
						//遍历数组,true 绘图 false 不绘制
						gd.fillRect(j*3+2, i*3+2, 3, 3);
					}
				}
			}
			
			//加载logo图片
			File file = new File("F:/blog1.jpg");//这里替换成自己本地图片
			Image srcImage = ImageIO.read(file);
			int imgWidth = srcImage.getWidth(null);
			int imgHeight = srcImage.getHeight(null);
			gd.drawImage(srcImage, (width-imgHeight)/2, (height-imgHeight)/2, imgWidth, imgHeight,null, null );
			
			//释放资源
			gd.dispose();
			bfImg.flush();
			//写入到指定路径
			ImageIO.write(bfImg, "png", new File(imgPath)); 
			System.out.println("二维码生产成功");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		getQrcodeImg("这里编辑想要生成的二维码内容", "f:/img.png(这里设置保存图片的位置)");
	}
}






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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值