JAVA生成一个二维码

通过JAVA生成一个二维码

提示:在java中生成二维码需要导入相应的jar包,jar包文末有链接

一、效果图


请添加图片描述

二、源代码

代码如下(示例):

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
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;

/*
 * @author: 魔王RK
 * @date: 2022/10/28
 * 二维码制作
 */
public class TestQRCode {

	public static void main(String[] args) throws WriterException, IOException {
		// TODO Auto-generated method stub
		MultiFormatWriter mfw=new MultiFormatWriter();
		//二维码内容
		String content = "Hello CSDN!";
		//设置为类型为常量
		BarcodeFormat type =BarcodeFormat.QR_CODE;
		//设置宽度
		int width=1080;
		//设置高度
		int height=1080;
		
		HashMap map =new HashMap();
		//设置编码
		map.put(EncodeHintType.CHARACTER_SET,"UTF-8");
		//设置纠错等级
		map.put(EncodeHintType.ERROR_CORRECTION,ErrorCorrectionLevel.L);
		//设置外边距为2px
		map.put(EncodeHintType.MARGIN,2);
		//画一个虚拟的二维码对象
		BitMatrix matrix=mfw.encode(content,type, width, height,map);
		
		//流虚拟二维码对象的信息写入电脑中
		
		//设置二维码颜色
		int black=Color.BLACK.getRGB();
		int white=Color.WHITE.getRGB();
		//生成二维码图像对象
		BufferedImage image=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		//设置像素
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				image.setRGB(x, y, matrix.get(x,y)?black:white);
			}
		}
		//这里我们设置文件目录
		File file=new File("F://one.jpg");
		//设置图片为jpg格式
		ImageIO.write(image, "jpg",file);
		
		
	}

}

三、相关资料

相关jar包链接:链接:https://pan.baidu.com/s/1ClUJSZSmvZTB4KnCjvEQhQ?pwd=lsgr
提取码:lsgr

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值