How do you resize an image using im4java?

2019-09-19 08:04发布

问题:

I'm trying to resize an image using im4java. I haven't found any working examples and their JavaDocs are incomplete.

OOTB Java solutions are insufficient and lead to poor quality in the resulting images, despite rendering hint adjustments.

回答1:

First of all, im4java is an interface for imagemagick and/or graphicsmagick, so you need to install one of them on your computer to get im4java to work.

Here is the code to resize an image:

ConvertCmd cmd = new ConvertCmd();

IMOperation op = new IMOperation();
op.addImage("original_image.jpg");
op.resize(800,600);
op.addImage("resized_image.jpg");

cmd.run(op);


回答2:

Do you really need this im4java ? I don't know it, but I use to do a pure java transformation :

public BufferedImage scale(final BufferedImage image, final int targetW, final int targetH)
    {
    final int type = image.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : image.getType();
    final BufferedImage scaledImg = new BufferedImage(targetW, targetH, type);
    final Graphics2D g = scaledImg.createGraphics();
    g.drawImage(image, 0, 0, targetW, targetH, null);
    g.dispose();
    g.setComposite(AlphaComposite.Src);
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    return scaledImg;
    }

this code has been working for me for more than 2 years in my project. Let me know if you have any question.