How to resize an image in Java?

Image can be resized in Java
Here is a simple method to re-size an image in Java. Here, you can also save the resized image in a file. The Image class contains the getScaledInstance() method which has the following prototype.
public Image getScaledInstance(int width, int height,int hints)

width, height is the width and height of the final image respectively.
hints corresponds to the algorithm used for re sizing. The possible values for hints are SCALE_DEFAULT, SCALE_FAST, SCALE_SMOOTH, SCALE_REPLICATE, SCALE_AREA_AVERAGING with values 1, 2, 4, 8, 16 respectively.

SCALE_DEFAULT: Use the default image-scaling algorithm.
SCALE_FAST:  This gives more priority to re-sizing rather than smoothness of the image.
SCALE_SMOOTH: This gives more priority to smoothing. Hence, quite slow.
SCALE_REPLICATE: This integrates more into image infrastructure provided by the toolkit.
SCALE_AREA_AVERAGING: This also integrates into the image infrastructure but in a different approach.

/*
This method is inherited to BufferedImage class from java.awt.Image class
public Image getScaledInstance(int width,int height,int hints);
*/

import javax.imageio.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
class ResizeImage
{
    public static void main(String args[]) throws Exception
    {
        // The first argument is the input file
        String file=args[0];
      
        // Take the output file
        String output=args[1];
      
        // Without extension? Go back
        if(!output.contains(".")) return;
      
        // Take the width,height as 2,3 args
        int w=Integer.parseInt(args[2]);
        int h=Integer.parseInt(args[3]);
      
        // Get the BufferedImage object by reading the image
        // from the given input stream
        BufferedImage bim=ImageIO.read(new FileInputStream(file));
      
        // I am using fast scaling
        Image resizedImg=bim.getScaledInstance(w,h,Image.SCALE_FAST);
      
        // Create a BufferedImage object of w,h width and height
        // and of the bim type
        BufferedImage rBimg=new BufferedImage(w,h,bim.getType());
      
        // Create Graphics object
        Graphics2D g=rBimg.createGraphics();
      
        // Draw the resizedImg from 0,0 with no ImageObserver
        g.drawImage(resizedImg,0,0,null);
      
        // Dispose the Graphics object, we no longer need it
        g.dispose();
      
        // Now, what? Just write to another file
      
        // The first argument is the resized image object
        // The second argument is the image file type, So i got the
        // extension of the output file and passed it
        // The next argument is the FileOutputStream to where the resized
        // image is to be written.
        ImageIO.write(rBimg,output.substring(output.indexOf(".")+1),new FileOutputStream(output));
      
    }
}
If you like this post, please share it. Also feel free to drop a comment.

No comments: