1. 程式人生 > 其它 >Windows下使用qrencode生成二維碼

Windows下使用qrencode生成二維碼

二維碼介紹

參考:
https://coolshell.cn/articles/10590.html#jtss-tsina
https://www.cnblogs.com/magicsoar/p/4483032.html

qrencode介紹

QR碼是當前最流行的二維碼之一,它具有可靠性高,識別速度快等特點.而qrencode則是一款由C語言(完全相容C++)寫成的一個QR碼生成與解碼的函式庫.它以GNU LGPL協議釋出。

靜態庫和動態庫的生成

參考:
https://blog.csdn.net/wzfgd/article/details/106230908

下載qrencode原始碼,使用cmake生成庫檔案。這裡要注意選擇的系統位數(32位和64位)和生成庫檔案的版本(debuge版和release版)。
這裡我提供一下Windows下32位的庫檔案(連結:

https://pan.baidu.com/s/1yHu2IxdR-5wYF41g0B81pA 提取碼:8888 ),64位自行操作。

獲取

 /**
 * @brief GernerateQRCode
 * 生成二維碼函式
 * @param text  二維碼內容
 * @param qrPixmap  二維碼畫素圖
 * @param scale 二維碼縮放比例
 */
void GernerateQRCode(const QString &text, QPixmap &qrPixmap, int scale)
{
       if(text.isEmpty())
    {
        return;
    }

    //二維碼資料
    QRcode *qrCode = nullptr;

    //這裡二維碼版本傳入引數是2,實際上二維碼生成後,它的版本是根據二維碼內容來決定的
    qrCode = QRcode_encodeString(text.toStdString().c_str(), 2,
                                 QR_ECLEVEL_Q, QR_MODE_8, 1);

    if(nullptr == qrCode)
    {
        return;
    }

    int qrCode_Width = qrCode->width > 0 ? qrCode->width : 1;
    int width = scale * qrCode_Width + 40;
    int height = scale * qrCode_Width + 40;

    QImage image(width, height, QImage::Format_ARGB32_Premultiplied);

    QPainter painter(&image);
    QColor background(Qt::white);
    painter.setBrush(background);
    painter.drawRect(0, 0, width, height);
    QColor foreground(Qt::black);
    painter.setBrush(foreground);
    for(int y = 0; y < qrCode_Width; ++y)
    {
        for(int x = 0; x < qrCode_Width; ++x)
        {
            unsigned char character = qrCode->data[y * qrCode_Width + x];
            if(character & 0x01)
            {
               QRect rect(x * scale +20, y * scale +20, scale, scale);
               painter.drawRects(&rect, 1);
            }
        }
    }
    painter.setBrush(foreground);
    painter.setFont(QFont("Arial",8));
    painter.drawText(12,15,"**智控科技");
    painter.setFont(QFont("Arial",5));
    painter.drawText(3,qrCode_Width+55,text);
    qrPixmap = QPixmap::fromImage(image);
    QRcode_free(qrCode);
}

呼叫

void slot_GenerateQRCode()
{
   QPixmap qrPixmap;
   GernerateQRCode(text, qrPixmap, 2);
   qrPixmap = qrPixmap.scaled(QSize(qrPixmap.width(), qrPixmap.height()),
                               Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
//     qrPixmap.save("./2021.png");
    ui->label_ShowQRCode->setPixmap(qrPixmap);
}

效果圖