Search code examples
imagemagickgraphicsmagickmagick++

How to construct Image from char buffer or string in Magick++


I need to construct an Image object from char * or std::string in Magick++. I've tried both ImageMagick and GraphicsMagick, but still can't work it out.

I first create a Blob object and use Image(const Blob &blob_) construct function to get an Image. Here is demo code:

//image is of type std::string
size_t len = image.size();
char *buf = new char[len + 1];
strncpy(buf, image.c_str(), len);
Blob blob(buf, len);
Image pic(blob);

But when I run it, I got error:

terminate called after throwing an instance of 'Magick::ErrorCoder'
  what():  Magick: JPEG datastream contains no image () reported by coders/jpeg.c:344 (JPEGErrorHandler)
Aborted

I found something about obtain string from Blob. So I created a Blob and update it via base64 method. But an error still occurred.

The only way I could think out is to save the char buffer in a temporary file and reload it via Image(const std::string &imageSpec_). However, this way is really unnecessary in my option.


Solution

  • The key problem is data type conversation. We can't convert char * to Blob directly. I found some demos in GraphicsMagick's source code. They provide the following way:

    1. string or char * => unsigned char *
    2. unsigned char * => const void *
    3. const void * => Blob

    Then the Image construction is OK. Or you can just try

    Magick::Blob blob(static_cast<const void *>(image.c_str()), len)