一、用到的库文件
stb_image.h (https://github.com/nothings/stb)仅需头文件即可,但是注意要在头文件包含时加上
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
否则可能会在编译时报错找不到库文件。
cairo 2.0 库(cairo是一个功能强大的2D图形库,专门用于提供绘制矢量图形的API。它支持多种绘图目标和多种图形图像格式,包括屏幕、图像文件、打印机等。cairo库通常用于创建高质量的矢量图形,它的应用领域涵盖了图像处理、数据可视化、图形界面等多个方面。)
二、代码
#include "cairo/cairo-pdf.h"
#include "cairo/cairo.h"
#include <iostream>
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
int insertBmpImage()
{
const char *input_filename = "input.bmp";
const char *output_filename = "output.pdf";
int width, height, channels;
unsigned char *image_data = stbi_load(input_filename, &width, &height, &channels, 0);
if (image_data == NULL)
{
fprintf(stderr, "Error loading image: %s\n", stbi_failure_reason());
return 1;
}
cairo_surface_t *surface = cairo_pdf_surface_create(output_filename, width, height);
cairo_t *cr = cairo_create(surface);
// Create RGB24 format image surface
cairo_surface_t *image_surface = cairo_image_surface_create(CAIRO_FORMAT_RGB24, width, height);
unsigned char *image_surface_data = cairo_image_surface_get_data(image_surface);
int stride = cairo_image_surface_get_stride(image_surface);
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int offset_in = (y * width + x) * channels;
int offset_out = (y * stride + x * 4);
image_surface_data[offset_out] = image_data[offset_in + 2]; // Red
image_surface_data[offset_out + 1] = image_data[offset_in + 1]; // Green
image_surface_data[offset_out + 2] = image_data[offset_in]; // Blue
}
}
// Draw the image surface to Cairo context
cairo_set_source_surface(cr, image_surface, 0, 0);
cairo_paint(cr);
// Cleanup
stbi_image_free(image_data);
cairo_surface_destroy(image_surface);
cairo_destroy(cr);
cairo_surface_finish(surface);
cairo_surface_destroy(surface);
printf("PDF file '%s' has been created\n", output_filename);
return 0;
}