通过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