imagemagick:将 MagickExportImagePixels 的输出 blob 保存到灰度图像文件?

imagemagick : saving MagickExportImagePixels's output blob to gray image file?

zbar 引擎示例源 (zbarimg.c) 显示如下。

https://github.com/ZBar/ZBar/blob/master/zbarimg/zbarimg.c

size_t bloblen = width * height;
unsigned char *blobdata = malloc(bloblen);
MagickExportImagePixels(images, 0, 0, width, height, "I", CharPixel, blobdata);

我想查看 blob 数据。 如何将 blob 数据保存到文件?

我制作了 save_imgdata 函数来保存 blob 数据。

int save_imgdata(char* imgf, int width, int height, char *raw)
{
    PixelWand *p_wand = NULL;
    PixelIterator *iterator = NULL;
    PixelWand **pixels = NULL;
    unsigned long x, y;
    char hex[128];

    //MagickWandGenesis();
    p_wand = NewPixelWand();
    PixelSetColor(p_wand, "gray");
    //PixelSetColor(p_wand, "white");
    MagickWand *m_wand = NewMagickWand(); //CORE_RL_wand_.lib;
    MagickSetImageDepth(m_wand, 8);
    MagickNewImage(m_wand, width, height, p_wand);
    // Get a new pixel iterator 
    iterator = NewPixelIterator(m_wand);
    for (y = 0; y<height; y++) {
        // Get the next row of the image as an array of PixelWands
        pixels = PixelGetNextIteratorRow(iterator, &x);
        // Set the row of wands to a simple gray scale gradient
        for (x = 0; x<width; x++) {
            sprintf(hex, "#%02x", *raw++);
            //sprintf(hex, "#%02%x02%x02x", *raw, *raw, *raw); raw++;
            PixelSetColor(pixels[x], hex);
        }
        // Sync writes the pixels back to the m_wand
        PixelSyncIterator(iterator);
    }
    MagickWriteImage(m_wand, imgf);
    DestroyMagickWand(m_wand);
    return 0;
}

调用save_imgdata("imgw.bmp",width,height,blobdata) 保存 24bpp 图像。

save_imgdata怎么了? 我想要它保存 8bpp 灰度图像文件。

不要费心迭代和构建动态 color/pixel 值 -- 它速度慢且资源密集。如果数据来自 export 方法,则使用 import 方法恢复。

int save_imgdata(char* imgf, int width, int height, void * raw)
{
    MagickWand * wand;
    PixelWand * bgcolor;

    bgcolor = NewPixelWand();
    PixelSetColor(bgcolor, "WHITE");
    wand = NewMagickWand();
    MagickNewImage(wand, width, height, bgcolor);
    bgcolor = DestroyPixelWand(bgcolor);
    MagickSetImageDepth(wand, 8);
    MagickSetImageColorspace(wand, GRAYColorspace);
    MagickImportImagePixels(wand, 0, 0, width, height, "I", CharPixel, raw);
    MagickQuantizeImage(wand,
                        256,             // Reduce to 8bpp
                        GRAYColorspace,  // Match colorspace
                        0,               // Calculate optimal tree depth
                        MagickTrue,      // Use dither ? This changes in IM-7
                        MagickFalse);    // Messure Error
    MagickWriteImage(wand, imgf);
    wand = DestroyMagickWand(wand);
    return 0;
}