1

I'm attempting to convert an image in an inputstream to an outputstream using im4java. FRom the docs, it looks like setting an inputProvider as the input and specifying an output stream should pipe the converted image, but i get a:

Failed to convert image: more argument images then placeholders

Here's my function:

public static InputStream convert(InputStream imageStream){
        try {
            // Set up the im4java properties. See {@link im4java}
            IMOperation op = new IMOperation();
            op.scale(1000);
            op.compress("Zip");
            ConvertCmd convert = new ConvertCmd();

            convert.setSearchPath(imLocation);

            logger.debug("Imagemagick located at: " + convert.getSearchPath());

            InputStream is = imageStream;
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            Pipe pipeIn = new Pipe (is, null);
            Pipe pipeOut = new Pipe(null, os);

            convert.setInputProvider(pipeIn);
            convert.setOutputConsumer(pipeOut);
            convert.run(op, "-", "pdf:-");
            is.close();
            os.close();

           pipeOut.consumeOutput(is);
           return is;
        }catch(Exception e){
            logger.debug("Failed to convert image: " + e.getMessage());
        }
        return null;
    }

Thanks!

roguequery
  • 964
  • 13
  • 28
  • not the answer to the question, but have you noted that you have closed `is` and after that you call `pipeOut.consumeOutput(is);` and you are returning closed `is`. Is that ok? I am not sure. –  Jun 18 '14 at 17:58

1 Answers1

2

Solved it, posting it here for posterity.

public static InputStream convert(String path, InputStream imageStream){
    try {
        IMOperation op = new IMOperation();
        op.compress("Zip");  //order matters here, make sure colorspace is the first arg set

        InputStream is = imageStream;
        Pipe pipeIn = new Pipe (is, null);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        Pipe pipeOut = new Pipe(null, os);
        ConvertCmd convert = new ConvertCmd();

        convert.setSearchPath(imLocation);

        convert.setInputProvider(pipeIn);
        convert.setOutputConsumer(pipeOut);

        op.addImage("-");
        op.addImage("pdf:-");
        // execute the operation
        final long startTime = System.nanoTime();
        convert.run(op);
        final long endTime = System.nanoTime();
        logger.debug("Compressed");
        logger.debug("done converting " + path);
        final long elapsedTimeInMs = (endTime - startTime) / 1000000;
        logger.debug("took " + elapsedTimeInMs);

        return new ByteArrayInputStream(os.toByteArray());
    }catch(Exception e){
        logger.debug("Failed to convert image: " + e.getMessage());
    }
    return null;
}
roguequery
  • 964
  • 13
  • 28