Image Resize

Following is sample Java code for reading an Image dimensions and to Resize image while preserving aspect ratio.


import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import javax.imageio.ImageIO;

public class ImageTest {
public static void main(String[] args) {
try {
System.out.println("Before reading...");
BufferedImage bi = readImage("D:\\temp\\itsecurity.jpg");
System.out.println("After reading...");

printImageProperties(bi);

BufferedImage scaledBufImg = scaleImageToWidth(bi, 200);

System.out.println("Writing new img...");
File modImg = new File("D:\\temp\\itsecurity_mod.jpg");
ImageIO.write(scaledBufImg, "jpeg", modImg);

} catch (Exception e) {
e.printStackTrace();
}
}

public static BufferedImage scaleImageToWidth(BufferedImage bi, int newWidth) throws Exception {
int iw = bi.getWidth();
int ih = bi.getHeight();
// Getting aspect ratio
double ratio = (double) iw / (double) ih;
// Calculate new height
int newheight = (int) (newWidth / ratio);
System.out.println("Scaling... " + newWidth + " X " + newheight);

// Get Scaled image
Image scaledImg = bi.getScaledInstance(newWidth, newheight, Image.SCALE_SMOOTH);

// Create new writable Image
BufferedImage scaledBufImg = new BufferedImage(newWidth, newheight, BufferedImage.TYPE_INT_RGB);
scaledBufImg.getGraphics().drawImage(scaledImg, 0, 0, null);
return scaledBufImg;
}

public static void printImageProperties(BufferedImage bi) throws Exception {
System.out.println("Dimensions(WxH):" + bi.getWidth() + " X " + bi.getHeight());
System.out.println("MinX:" + bi.getMinX() + ", MinY:" + bi.getMinY());
}

public static BufferedImage readImage(String path) throws Exception {
File imageFile = new File(path);
InputStream is = new FileInputStream(imageFile);
BufferedImage bi = ImageIO.read(is);
return bi;
}

public static BufferedImage readImage(byte[] bytes) throws Exception {
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
BufferedImage bi = ImageIO.read(bis);
return bi;
}
}

No comments: