chasep255
chasep255

Reputation: 12175

How to make image magic convert output ppm to stdout

I am writing some image processing routines. My image class supports reading and writing images in the ppm (P6) format. To use other types of images I wanted to convert them to a ppm through image magic convert. To do this I need convert to write the contents of the ppm to stdout since I am reading them with a pipe (note that creating temporary files in not acceptable).

Right now I have this code.

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

The command the popen is using is as follows. convert "/home/chase/Desktop/m27.jpg" -depth 16 -format ppm /dev/stdout

When I run this in the terminal I am not getting proper PPM output since the first line of the files does not start with P6. What would be the proper command line to do this?

Upvotes: 1

Views: 1690

Answers (2)

Mark Setchell
Mark Setchell

Reputation: 207425

You probably want:

convert input.jpg -depth 16 ppm:

which will give you P6 binary data, or

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

which will give you P3 ASCII data

Upvotes: 3

coincoin
coincoin

Reputation: 4685

You need to force an ascii mode output with the option -compress none. By default imagemagick generates in raw (P6) mode.

Therefore this line should do the work (assuming the rest of your code works) :

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

From the 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.

Upvotes: 2

Related Questions