#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <png.h>
#include <qrencode.h>
void save_png(const char *filename, unsigned char *data, int width, int height);
int main() {
// 要编码成二维码的字符串
const char *text = "https://example.com";
// 生成二维码
QRcode *qrcode = QRcode_encodeString(text, 0, QR_ECLEVEL_Q, QR_MODE_8, 1);
// 将二维码放大到800x800
int scale = 800 / qrcode->width;
int size = qrcode->width * scale;
unsigned char *buffer = (unsigned char *)malloc(size * size);
for (int y = 0; y < size; y++) {
for (int x = 0; x < size; x++) {
buffer[y * size + x] = qrcode->data[y / scale * qrcode->width + x / scale] & 1 ? 0 : 255;
}
}
// 保存为PNG文件
save_png("qrcode.png", buffer, size, size);
// 释放内存
QRcode_free(qrcode);
free(buffer);
return 0;
}
void save_png(const char *filename, unsigned char *data, int width, int height) {
FILE *fp;
png_structp png_ptr;
png_infop info_ptr;
fp = fopen(filename, "wb");
if (!fp) {
fprintf(stderr, "Error: Unable to open file %s for writing\n", filename);
return;
}
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!png_ptr) {
fclose(fp);
fprintf(stderr, "Error: Unable to create PNG write structure\n");
return;
}
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_write_struct(&png_ptr, NULL);
fclose(fp);
fprintf(stderr, "Error: Unable to create PNG info structure\n");
return;
}
png_init_io(png_ptr, fp);
png_set_IHDR(png_ptr, info_ptr, width, height, 8, PNG_COLOR_TYPE_GRAY,
PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
png_write_info(png_ptr, info_ptr);
for (int y = 0; y < height; y++) {
png_write_row(png_ptr, data + y * width);
}
png_write_end(png_ptr, info_ptr);
png_destroy_write_struct(&png_ptr, &info_ptr);
fclose(fp);
}
09-24
1011
06-07
922
02-08
4225
03-12
6257
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交