java

How to resize an image in Java

In this tutorial, we are going to see how to resize an image in Java. In Java, to resize (or scale) an image and save it, we can follow these steps:

  1. Create a BufferedImage object for the input image by calling the read() method of the ImageIO class.
  2. Create a BufferedImage object for the output image with a desired width and height.
  3. Get a Graphics2D object from the BufferedImage object of the output image.
  4. Draw the BufferedImage object of the input image on the Graphics2D object of the output image.
  5. Save the output image to a file using the write() method of the ImageIO class.
 

How to resize an image in Java
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.*;

 
public class ResizeImg 
{
 public static void changeSize(String inImg, String outImg, int w, int h)
 throws IOException 
 {
      // reads the input image
      File f = new File(inImg);
      BufferedImage inputImage = ImageIO.read(f);
 
      // creates the output image
      BufferedImage img = new BufferedImage(w, h, inputImage.getType());
 
      // balance the input image to the output image
      Graphics2D g = img.createGraphics();
      g.drawImage(inputImage, 0, 0, w, h, null);
      g.dispose();
 
      // extract the extension of the output file
      String name = outImg.substring(outImg.lastIndexOf(".") + 1);
 
      // writes to the output file
      ImageIO.write(img, name, new File(outImg));
 }
 
 public static void main(String[] args) 
 {
        String inImg = "test.jpg";
        String outImg = "test_1200x628.jpg";
 
        try 
        {
            //width and height of the output image
            int width = 1200;
            int height = 628;
            ResizeImg.changeSize(inImg, outImg, width, height);
        }
        catch (IOException ex) 
        {
            ex.printStackTrace();
        }
 }
}
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *