美文网首页
c语言使用qrencode库实现二维码

c语言使用qrencode库实现二维码

作者: 一路向后 | 来源:发表于2021-01-24 23:02 被阅读0次

    1.源码实现

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <qrencode.h>
    #include <cairo.h>
    
    int main()
    {
        cairo_surface_t *surface;
        cairo_t *cr;
        QRcode *qr = NULL;
        QRecLevel level = QR_ECLEVEL_L;
        QRencodeMode hint = QR_MODE_8;
        char *msg = "Hello World";
        int version = 1;
        int casesensitive = 1;
        unsigned char *qrData = NULL;
        int width = 0;
        int height = 0;
        int i, j;
    
        qr = QRcode_encodeString(msg, version, level, hint, casesensitive);
        if(qr == NULL)
        {
            printf("QRcode encodeString error!\n");
            return -1;
        }
    
        surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 300, 300);
            cr = cairo_create(surface);
            cairo_set_source_rgb(cr,0,0,0);
    
        qrData = qr->data;
        width = qr->width;
        height = qr->width;
    
        //printf("(%d, %d)\n", width, height);
    
        for(i=0; i<height; i++)
        {
            for(j=0; j<width; j++)
            {
                if(qrData[i*width+j] & 1)
                {
                    //printf("(%d, %d)\n", i, j);
                    cairo_rectangle(cr,45+i*10,45+j*10,10,10);
                    cairo_fill(cr);
                }
            }
        }
    
        cairo_surface_write_to_png(surface, "a.png");
        cairo_destroy(cr);
    
        QRcode_free(qr);
    
        return 0;
    }
    

    2.编译源码

    $ gcc -o example example.c -I$HOME/local/include -I/usr/include/cairo -L$HOME/local/lib  -lqrencode -lcairo
    

    3.运行程序

    $ ./example
    

    4.结果查看

    a.png

    相关文章

      网友评论

          本文标题:c语言使用qrencode库实现二维码

          本文链接:https://www.haomeiwen.com/subject/wubvzktx.html