Image resize - Preserving Image Size : Java

Posted by Jagadeesh VP | Posted in

Resizing the image by fixed width and height some times go bad. The dimensions of the image should be preserved while resizing.

I thing the below logic will help to solve this problem.

private BufferedImage resizeImage(File imageFile) {
   int width = 250;
   int height = 250;

   BufferedImage image = null;
   try {
      image = ImageIO.read(imageFile);
   } catch (IOException e) {

   }


   if (image.getWidth() < width && image.getHeight() < height) {
      return image;
   
   } else if (image.getWidth() > image.getHeight()) {
      float percent = (250f / image.getWidth()) * 100;
      height = ((image.getHeight() * (int) percent) - image.getHeight()) / 100;
 
   } else {
      float percent = (250f / image.getHeight()) * 100;
      width = ((image.getWidth() * (int) percent) - image.getWidth()) / 100;
  
   }


   BufferedImage resizedImage = new BufferedImage(width, height, image.getType());
   Graphics2D g = resizedImage.createGraphics();
   g.drawImage(image, 0, 0, width, height, null);
   g.dispose();
   return resizedImage;
}

Comments (1)

Great Code. Thank you so much, works like a charm.

Post a Comment