2

I'm using im4java library for image processing operations with ImageMagick.

The code I'm using looks like:

ImageCommand imageCommand = new ConvertCmd();
imageCommand.setSearchPath(getImageMagickPath());
operation = new IMOperation();
operation.quality(100d);
operation.addImage();
operation.resize(getWidth());
operation.addImage();
imageCommand.run(operation, sourceImage, extention);

But the quality of resulting image is bad. Doing the same thing using command line gives 4 times bigger size with better quality. Are there any additional settings should be set when using im4java? The file format is jpg. Thanks in advance...

Czarina
  • 21
  • 1
  • 2

1 Answers1

0

This is the code I'm using, and it works like charm:

    private static void saveScaleImage(File image, String outputImagePath, int width, Integer height, float quality, boolean fill) throws Exception {
        Info info = new Info(image.getPath(), true);
        String imageFormat = info.getImageFormat();
        IMOperation op = new IMOperation();
        op.addImage(imagen.getPath());
        int imageWidth = info.getImageWidth(),
            imageHeight = info.getImageHeight();
        if (imageWidth> 0 && imageHeight > 0 && (imageFormat == null || !imageFormat.equalsIgnoreCase("TIFF"))) {
            //fill transparencies && extra space with white
            op.size(imageWidth, imageHeight);
            op.addRawArgs("xc:white");
            op.addImage(outputImagePath);
            // set up command
            CompositeCmd composite = new CompositeCmd();
            composite.run(op);
            op = new IMOperation();
            op.addImage(outputImagePath);
        }
        //add strip irrelevant info
        op.strip();
        //resize
        if (fill) { //crop image + fill
            op.resize(width, height, "^").gravity("center").extent(width, height);
        } else { //adjust
           op.resize(width, height);
        }
        boolean smaller = imageWidth > 0 && imageHeight > 0 && imageWidth < width && imageHeight < width;
        if (smaller) {
            op.addImage(outputImagePath);
            op.gravity("center");
        }
        if (imageFormat == null || imageFormat.equalsIgnoreCase("PNG")) {
            //jpeg teawks
            op.type("optimize").quality((double) quality).blur(0d, .16);
            //default to jpeg format
            op.addImage("jpeg:" + outputImagePath);
        } else {
            op.addImage(outputImagePath);
        }
        // set up command
        ConvertCmd convert = new ConvertCmd();
        //run command
        convert.run(op);
    }
I.G. Pascual
  • 5,818
  • 5
  • 42
  • 58