Jul 26, 2007

Resizing Images with Java

Sample code to resize image with Java.
Because I couldn't find proper ImageWriter GIF format changed to PNG.
When you use this on UNIX like Opearating Systems without X Window ,you need one of the followings

-Djava.awt.headless=true starting option
-PJA
-Xvfb

import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.imageio.stream.*;
public class Twinspark{
public static void main(String[] args){
if(args.length < 2){
System.out.println("Usage:");
System.out.println(" java Twinspark InputImageFile OutPutWidthInPixel");
System.exit(0);
}
String inputFileName = args[0];
int outputWidth = 0;
try{
outputWidth = Integer.parseInt(args[1]);
}catch(Throwable e){
System.out.println("OutPutWidthInPixel must be in Integer!");
e.printStackTrace();
System.exit(0);
}

if(outputWidth == 0){
System.out.println("OutPutWidthInPixel must be larger than 0!");
}

BufferedImage image = null;
try{
File inputFile = new File(inputFileName);
image = ImageIO.read(inputFile);
}catch(IOException e){
System.out.println("InputFile is not Found!");
e.printStackTrace();
System.exit(0);
}
String extension = inputFileName.substring(inputFileName.lastIndexOf(".") +1);
if(extension.toUpperCase().equals("GIF")){
extension = "png";
inputFileName = inputFileName.toLowerCase().replaceAll("\\.gif",".png");
}
Image outputImage = image.getScaledInstance(outputWidth,-1,Image.SCALE_SMOOTH);
BufferedImage bffImg = new BufferedImage(outputWidth,image.getHeight(null)* outputWidth /image.getWidth(null),BufferedImage.TYPE_3BYTE_BGR);
Graphics offg = bffImg.createGraphics();
offg.drawImage(outputImage, 0, 0, null);

try{
File outputFile = new File("after_" + inputFileName);
FileImageOutputStream fio = new FileImageOutputStream(outputFile);
ImageWriter iw = (ImageWriter) (ImageIO.getImageWritersBySuffix(extension)).next();

iw.setOutput(fio);
iw.write(bffImg);

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

2 comments:

Anonymous said...

http://www.comesolvego.com/2008/04/29/resize-images-with-java-high-quality-and-working-solution/

Anonymous said...

Thanks for writing this.