0

I am using Cairo to render an image, and I have an issue that the canvas always drawing with blank (no image was drawn). Please refer my code below:

int width, height, channels;
unsigned char* data = stbi_load(imagePath.c_str(), &width, &height, &channels, STBI_rgb_alpha);
int stride = cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, width);
this->imageSource = cairo_image_surface_create_for_data(data, CAIRO_FORMAT_ARGB32, width, height, stride);
free(data);

But if I render png file using currently supported function from Cairo, it's working well, my code below:

this->imageSource = cairo_image_surface_create_from_png(imagePath.c_str());
Dominique
  • 16,450
  • 15
  • 56
  • 112
Lý Hoài
  • 129
  • 6

1 Answers1

0

The problem was found by myself. it's because of the memory free, so the data pointer of cairo is refer to empty data. I solved it by using other api of cairo (cairo_image_surface_create) instead of cairo_image_surface_create_for_data. See my code below:

//define params
int width, height, channels;
//read image data from file using stb_image.h
unsigned char* data = stbi_load(imagePath.c_str(), &width, &height, &channels, STBI_rgb_alpha);
//create surface with image size and format is ARGB32
this->imageSource = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height);
//get pointer of cairo data
unsigned char * surface_data = cairo_image_surface_get_data(this->imageSource);
//copy current data to surface pointer
memcpy(surface_data, data, width * height * 4 * sizeof(unsigned char));
//mark as dirty to refresh surface
cairo_surface_mark_dirty(this->imageSource);
//free image data
free(data);
Lý Hoài
  • 129
  • 6