C++实现使用std_image加cairo库实现多种图片插入绘制生成PDF、PNG文件

一、用到的库文件

        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;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值