QRcode*
QRcode_encodeString(
const char* string,
int version,
QRecLevel level,
QRencodeMode hint,
int casesensitive
)
将字符串编码到二维码中。
const char* string
是要编码的字符串。
int version
表示生成的二维码的相对尺寸
。取值范围为[4 ~ 40]
。传入0
就相当于4
。
QRecLevel
表示容错等级
,其定义如下:
typedef enum {
QR_ECLEVEL_L = 0, // lowest
QR_ECLEVEL_M,
QR_ECLEVEL_Q,
QR_ECLEVEL_H // highest
} QRecLevel;
QRencodeMode
表示提示信息
,其定义如下:
typedef enum {
QR_MODE_NUL = -1, // Terminator (NUL character). Internal use only
QR_MODE_NUM = 0, // Numeric mode
QR_MODE_AN, // Alphabet-numeric mode
QR_MODE_8, // 8-bit data mode
QR_MODE_KANJI, // Kanji (shift-jis) mode
QR_MODE_STRUCTURE, // Internal use only
QR_MODE_ECI, // ECI mode
QR_MODE_FNC1FIRST, // FNC1, first position
QR_MODE_FNC1SECOND, // FNC1, second position
} QRencodeMode;
int casesensitive
表示英文字母是否大小写敏感。1:true 0:false
。
QRcode
表示编码后的数据,其定义如下:
typedef struct {
int version; // version of the symbol
int width; // width of the symbol
unsigned char *data; // symbol data
} QRcode;
int width
表示点阵在水平方向上的点的个数。因为二维码是正方形的,所以,在竖直方向上点的个数与水平方向一样。
unsigned char *data
表示点阵的数据,1
表示黑色
,0
表示白色
。
运行成功
时,返回值不为NULL
。
运行失败
时,返回值为NULL
。并设置了errno
变量的值,其值可能有如下:
error | 说明 |
---|---|
EINVAL | invalid input object. |
ENOMEM | unable to allocate memory for input objects. |
ERANGE | input data is too large. |
step1、编写一个C语言源程序qrencodeTest.c
,其内容如下
#include <qrencode.h>
#include <stdio.h>
int main(int argc, char* argv[]) {
if (1 == argc) {
printf("please provide a string to encode.\n");
return 1;
}
QRcode* qrcode = QRcode_encodeString(argv[1], 1, QR_ECLEVEL_H, QR_MODE_8, 1);
if (!qrcode) {
extern int errno;
printf("error occurred. code is %d\n", errno);
return errno;
}
int i, j, width = qrcode->width;
for (i = 0; i < width; i++) {
for (j = 0; j < width; j++) {
if (qrcode->data[(i * width) + j] & 0x1) {
printf("\033[40m \033[0m");
} else {
printf("\033[47m \033[0m");
}
}
printf("\n");
}
QRcode_free(qrcode);
return 0;
}
注意:这里仅仅是为了简单展示该函数的用法,所以将它用空白字符
的黑色背景
和白色背景
表示点阵的1
和0
, 实际使用中,你可能要结合PNG、BMP等编码技术,编码成相应的图片。
step2、使用cc命令进行编译
cc -o qrencodeTest -lqrencode qrencodeTest.c
step3、运行qrencodeTest
./qrencodeTest http://blog.fpliu.com/it
得到如下输出:
使用微信 → 扫一扫
,即可解码成功。