Search code examples
cimagemagick

Save image in memory and not in disk using C API in ImageMagick


I have this command line:

 \ImageMagick-7.0.8-Q16\magick.exe -background transparent -fill white -font Amiri-Bold -pointsize 100 -kerning 5.0 -gravity center label:@c:\users\foo\appdata\local\temp\tmpahpcw2.txt -type truecolormatte PNG32:c:\users\foo\appdata\local\temp\tmp1ogyjm.png 

As you see it takes the string from file and save it to png file. Can I do the same operation using the C API? (I guess yes). But the important issue is not using files on disk only in memory.


Solution

  • If you want to save the PNG image file to memory, use MagickGetImageBlob.

    size_t length;
    unsigned char * address;
    address = MagickGetImageBlob(wand, &length);
    if (address != (unsigned char *)NULL) {
      printf("Wrote %zu bytes of data to %p address\n", length, address);
    }
    

    If you want to save the pixel data to memory, use MagickExportImagePixels.

    MagickBooleanType status;
    size_t width = MagickGetImageWidth(wand);
    size_t height = MagickGetImageHeight(wand);
    size_t channels = 3; // "RGB"
    size_t data_length = sizeof(unsigned char) * channels * width * height;
    unsigned char * data = malloc(data_length);
    status = MagickExportImagePixels(wand, 0, 0, width, height, "RGB", CharPixel, data);
    if (status == MagickTrue) {
      fprintf(stdout, "Wrote %zu bytes of data to %p address\n", data_length, data);
    }