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

时间:2018-03-14 03:22:24

标签: imagemagick zbar

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);

我想看看blobdata。 如何将blobdata保存到文件?

我制作了save_imgdata函数来保存blobdata。

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的调用(&#34; imgw.bmp&#34;,width,height,blobdata) 保存24bpp图像。

save_imgdata有什么问题? 我想保存8bpp灰色图像文件。

1 个答案:

答案 0 :(得分:1)

不要费心迭代和构建动态颜色/像素值 - 这是缓慢且资源密集的。如果数据来自 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;
}