如下图能够通过字符串生成二维码
编程环境
- 二维码编码:Qt5.14 + qrcode库
- 二维码解码:Qt5.14 + QZXing库
- qrcode库下载地址:https://fukuchi.org/works/qrencode/
- QZXing库下载地址:https://github.com/ruisebastiao/QZXing
1 二维码编码
1.1环境配置
下载qrcode库后,解压后只留下下图红框所框住的文件
其中将config.h.in更名为 config.h 在文件中将MAJOR_VERSION、 MICRO_VERSION、MINOR_VERSION 、VERSION要在对应的#undef下方添加下图定义
#define MAJOR_VERSION 1
#define MICRO_VERSION 1
#define MINOR_VERSION 1
#define VERSION 1
同时在pro文件中加入
DEFINES += HAVE_CONFIG_H
1.2了解qrencode库
qrencode是开源的二维码QR码编码库,主要C语言编写的,这样方便移植到各种平台下。QR Code码特点如图一所示。
QRcode结构体中,qrcode->data包含了二维码图像的信息,其中每个数据中的bit0位代表了点的颜色,1表示黑色,0表示白色。
1.3编写代码
然后就可以将上面所挑选的文件加入工程,然后就可以使用qrcode库,如下图所示可以通过字符串来输出对应二维码的QImage。
QImage QrCode::StringTo_QrCodeImage(QString codestr, int imagew, int imageh)
{
QRcode *qrcode;
qrcode=QRcode_encodeString(codestr.toStdString().c_str(),2,QR_ECLEVEL_Q,QR_MODE_8,1);
qint32 temp_width = imagew;
qint32 temp_height = imageh;
qint32 qrcode_width=qrcode->width>0?qrcode->width:1;
double scale_x=(double)temp_width/(double)qrcode_width;
double scale_y=(double)temp_height/(double)qrcode_width;
QImage mainimg=QImage(temp_width,temp_height,QImage::Format_ARGB32);
QPainter painter(&mainimg);
QColor background(Qt::white);
painter.setBrush(background);
painter.setPen(Qt::NoPen);
painter.drawRect(0,0,temp_width,temp_height);
QColor foreground(Qt::black);
painter.setBrush(foreground);
unsigned char* pqrdata = qrcode->data;
for(qint32 y = 0; y < qrcode_width; ++y) {
for(qint32 x = 0; x < qrcode_width; ++x) {
if((*pqrdata++) &0x01) {
QRectF r(x*scale_x, y*scale_y, scale_x, scale_y);
painter.drawRects(&r, 1);
}
}
}
QRcode_free(qrcode);
return mainimg;
}
2 二维码解码
2.1环境配置
下载QZXing库后,在pro文件中加入下面的代码,将下面的QZXing.pri文件加入工程中
include($$PWD/qzxing/QZXing.pri)
定义下面变量
DEFINES += __STDC_LIMIT_MACROS
2.2编写代码
QZXing decoder;
decoder.setDecoder( QZXing::DecoderFormat_Aztec |
QZXing::DecoderFormat_CODABAR |
QZXing::DecoderFormat_CODE_39 |
QZXing::DecoderFormat_CODE_93 |
QZXing::DecoderFormat_CODE_128 |
QZXing::DecoderFormat_DATA_MATRIX |
QZXing::DecoderFormat_EAN_8 |
QZXing::DecoderFormat_EAN_13 |
QZXing::DecoderFormat_ITF |
QZXing::DecoderFormat_MAXICODE |
QZXing::DecoderFormat_PDF_417 |
QZXing::DecoderFormat_QR_CODE |
QZXing::DecoderFormat_RSS_14 |
QZXing::DecoderFormat_RSS_EXPANDED |
QZXing::DecoderFormat_UPC_A |
QZXing::DecoderFormat_UPC_E |
QZXing::DecoderFormat_UPC_EAN_EXTENSION);
qDebug()<<decoder.decodeImage(mainimg);
全部源码已经放在CSDN上了,地址为https://download.csdn.net/download/qq_40732350/13095121