使用java生成二维码的代码

package com.guandong;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class Code {
	// 获取二维码图片
	public void getCode(int width, int height, String content, String path, String type) {
		// 设置二维码的基本信息(纠错等级设置,留白,字符集)
		// Map
		Map map = new HashMap();
		// 添加数据
		map.put(EncodeHintType.CHARACTER_SET, "utf-8");
		map.put(EncodeHintType.MARGIN, 2);
		// L(7%) M(%15) Q(%25) H(%30)
		map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
		// 输出二维码,二维码输出流
		MultiFormatWriter mu = new MultiFormatWriter();

		// 生成二维码
		try {
			BitMatrix bit = mu.encode(content, BarcodeFormat.QR_CODE, width, height);

			// 画图
			BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

			// 绘制二维码上的点
			for (int i = 0; i < width; i++) {
				for (int j = 0; j < height; j++) {
					// get(i, j)有没有值,有值得话就打印一个黑点,反之就是白色
					int rgb = bit.get(i, j) ? Color.BLACK.getRGB() : Color.white.getRGB();
					img.setRGB(i, j, rgb);
				}
			}

			// 将图片输出到指定位置
			// 通过File来描述位置对象
			File file = new File(path);
			// 将图片写入到文件中
			boolean flag = ImageIO.write(img, type, file);
			if (!flag) {
				System.out.println("没有成功");
			}else {
				System.out.println("请查看");
			}
		} catch (WriterException e) {
			e.printStackTrace();
		} catch (IOException e) {

			e.printStackTrace();
		}

	}
	
	public static void main(String[] args) {
		new Code().getCode(400, 400, "http://www.baidu.com",  "D:/a.jpg","jpg");
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值