While working with applications involving Photos, we may come across a situation where the actual photo size is not as per our need and we need to resize the images to meet the dimension needs while maintaining the aspect ratio without losing the picture quality.
In java, we can make use of image editing features provided in java.awt.image package and also javax.imageio package to resize pictures.
In this post, I am going to explain complete java code for image resizing which contains a main method and a resize method. The resize method expects following parameters:
1. Source Image name with full path
2. Resized image name with full path
3. Width (pixels) for resized image.
The method resizes the image and sends back the response (success message or exception message if there is any exception).
The source file being used for this example is iqbal.png which has a size 254×198. When calling the resize method from the main method; width value is specified as 200 so that resized image has a width of 200 pixels and height ratio is maintained.
Below is the complete code for image resizing in Java
public class ResizeImage
public static void main(String args) throws Exception
// Call static method to resize an image to 200 pixels width
String result_message= resize(“C:\Pics\iqbal.png”,”C:\Pics\resized_pic.png”,200);
// This method will resize the image to the specified width and will maintain aspect ratio for the height of the picture to maintain quality
public static String resize(String sourceFile, String ResizedFile, int width) throws Exception
File f = new File(sourceFile);
return “File doesn’t exist”;
// Logic to implement image resizing
BufferedImage bim=ImageIO.read(new FileInputStream(sourceFile));
BufferedImage rBimg=new BufferedImage(width,scaled_height,bim.getType());
// Create Graphics object
Graphics2D g=rBimg.createGraphics();// Draw the resizedImg from 0,0 with no ImageObserver
// Dispose the Graphics object, we no longer need it
catch (Exception e)
return “Picture Resized Successfully”;
After compiling this code and running it; you will get the new picture created in the specified location with the name resized_pic.java and the new image will have a width of 200 pixels and height will be based on the aspect ratio without losing picture quality.