如何使图像魔术将输出 ppm 转换为标准输出

How to make image magic convert output ppm to stdout

我正在写一些图像处理例程。我的图片class支持读写ppm(P6)格式的图片。要使用其他类型的图像,我想通过图像魔术转换将它们转换为 ppm。为此,我需要转换以将 ppm 的内容写入标准输出,因为我正在使用管道读取它们(请注意,创建临时文件是不可接受的)。

现在我有这个代码。

void Image::read(const char* file)
{
    std::string cmd = std::string("convert \"") + file + std::string("\" -depth 16 -format ppm /dev/stdout");

    std::cout << cmd << std::endl;

    FILE* f = popen(cmd.c_str(), "r");
    img_assert(f, "Could not start conversion process.");

    try
    {
        read_ppm(f);
    }
    catch(...)
    {
        pclose(f);
        img_assert(false, "Conversion failed.");
    }

    pclose(f);
}

popen使用的命令如下。 convert "/home/chase/Desktop/m27.jpg" -depth 16 -format ppm /dev/stdout

当我 运行 在终端中执行此操作时,我无法获得正确的 PPM 输出,因为文件的第一行不是以 P6 开头。执行此操作的正确命令行是什么?

您需要使用选项 -compress none 强制使用 ascii 模式输出。 默认情况下,imagemagick 以原始 (P6) 模式生成。

因此这一行应该完成工作(假设您的其余代码有效):

std::string cmd = std::string("convert \"") + file + std::string("\" -depth 16 -compress none -format ppm /dev/stdout");

来自doc :

PNM is a family of formats supporting portable bitmaps (PBM) , graymaps (PGM), and pixmaps (PPM). There is no file format associated with pnm itself. If PNM is used as the output format specifier, then ImageMagick automagically selects the most appropriate format to represent the image. The default is to write the binary version of the formats. Use -compress none to write the ASCII version of the formats.

你可能想要:

convert input.jpg -depth 16 ppm:

这会给你 P6 二进制数据,或者

convert input.jpg -depth 16 -compress none ppm:

这将为您提供 P3 ASCII 数据