将BLOB读取到图像时出现Magick++错误

Magick++ Error when reading BLOB into Image

本文关键字:Magick++ 错误 图像 BLOB 读取      更新时间:2023-10-16

我正试图使用Magick++库将原始像素数据中的图像导出到RGBA PNG中。

然而,当我试图运行它时,我遇到了一个奇怪的错误:

terminate called after throwing an instance of 'Magick::ErrorCorruptImage'
  what():  test: unexpected end-of-file `': No such file or directory @ error/rgb.c/ReadRGBImage/229
Aborted

这是相关的代码部分(我省略了填充像素向量,但这并没有改变任何东西):

#include <iostream>
#include <vector>
#include <ImageMagick/Magick++.h>
using namespace std;
int main(int argc, char *argv[]) {
    Magick::InitializeMagick(*argv);
    int rres, ires;
    cin >> rres >> ires;
    //RGBA
    //rres: horiz. resolution, ires: vert. resolution
    vector<unsigned char> image(rres * ires * 4);
    Magick::Blob blob(&image[0], rres*ires*4);
    Magick::Image img;
    img.size(to_string(rres) + "x" + to_string(ires));
    img.magick("RGBA");
    img.read(blob);
    img.write("out.png");
}

编译:

g++ --std=c++11 -O0 -g3 -ggdb3 -D_GLIBCXX_DEBUG -Wall test.cpp -o test `Magick++-config --cppflags --cxxflags --ldflags --libs`

如果您使用的是ImageMagick的Q8版本,那么您的示例就可以工作。但您似乎使用的是ImageMagick的Q16版本。后者每像素通道使用16位。您正在使用向量<无符号字符>,其仅为8位。我建议您切换到向量<无符号短>或使用向量<无符号字符>是当前大小的两倍。如果每个像素通道不需要16位,您也可以切换到ImageMagick的Q8版本。