SomeoneInNeedOfHelp
SomeoneInNeedOfHelp

Reputation: 31

Java - How to pad and resize image without cropping?

I need to resize alot of images from the ratio aspect (2:3) to (3:4).

The images are 800px x 1200px currently. I need them to be 600px x 800px eventually without any cropping.

May I know what libraries are available for me to do padding and resizing without cropping in Java?

Upvotes: 2

Views: 1637

Answers (3)

azro
azro

Reputation: 54148

From your current Image (assuming a java.awt.Image) you can use :

And these steps:

  • compute the ratios in width and in height
  • depending on their values (padding width or padding height)
    • compute the width and height to obtain the scaled image
    • compute the padding required
  • write the image at the good position
static BufferedImage pad(BufferedImage image, double width, double height, Color pad) {
    double ratioW = image.getWidth() / width;
    double ratioH = image.getHeight() / height;
    double newWidth = width, newHeight = height;
    int fitW = 0, fitH = 0;
    BufferedImage resultImage;
    Image resize;

    //padding width
    if (ratioW < ratioH) {
        newWidth = image.getWidth() / ratioH;
        newHeight = image.getHeight() / ratioH;
        fitW = (int) ((width - newWidth) / 2.0);

    }//padding height
    else if (ratioH < ratioW) {
        newWidth = image.getWidth() / ratioW;
        newHeight = image.getHeight() / ratioW;
        fitH = (int) ((height - newHeight) / 2.0);
    }

    resize = image.getScaledInstance((int) newWidth, (int) newHeight, Image.SCALE_SMOOTH);
    resultImage = new BufferedImage((int) width, (int) height, image.getType());
    Graphics g = resultImage.getGraphics();
    g.setColor(pad);
    g.fillRect(0, 0, (int) width, (int) height);
    g.drawImage(resize, fitW, fitH, null);
    g.dispose();

    return resultImage;
}

To use as

BufferedImage image = ...;
BufferedImage result = pad(image, 600, 800, Color.white);

Upvotes: 4

SomeoneInNeedOfHelp
SomeoneInNeedOfHelp

Reputation: 31

Managed to do it using below code: 'w' is the amount of padding you need on each side.

BufferedImage newImage = new BufferedImage(image.getWidth()+2*w, image.getHeight(), 
image.getType());

Graphics g = newImage.getGraphics();

g.setColor(Color.white);
g.fillRect(0,0,image.getWidth()+2*w,image.getHeight());
g.drawImage(image, w, 0, null);
g.dispose();

Upvotes: 1

dpatil
dpatil

Reputation: 9

I think ffmpeg can help you to do anything with image. e.g. Use ffmpeg to resize image

  1. You can keep ffmpeg binaries in some conf folder.
  2. Create sh script for ffmpeg command.
  3. Use CommandLine from (Apache Commons exec library) to run the script.

Upvotes: 0

Related Questions