Search code examples
javaimagemagickim4java

im4java and imagemagick - why gravity parameter is not working?


I'm trying to resize an image using Image Magick through IM4Java library.

It works well, except the image isn't centered. I've run these same commands through external command line and they work well.

Can anyone tell me why this isn't working?

private void convertImage(int width, int height, String source, String dest)
        throws IOException, IM4JavaException, InterruptedException
{
    // create command
    ConvertCmd cmd = new ConvertCmd();

    // create the operation, add images and operators/options
    IMOperation op = new IMOperation();
    op.addImage(source);

    op.thumbnail(width, height, ">");
    op.extent(width, height);
    op.gravity("center");
    op.background("white");

    op.addImage(dest);
    ProcessStarter.setGlobalSearchPath("/usr/local/bin");
    cmd.setOutputConsumer(imageMagickOutputter);
    cmd.run(op);

}

The result of the command with background switched to blue


Solution

  • The order of the operations matters: put the gravity operation before thumbnail and extent:

            IMOperation op = new IMOperation();
            op.addImage(sourceFile);
            op.gravity("center");
            op.thumbnail(width, height, '^');
            op.extent(width,height);
            op.addImage(destinationFile);