Tuesday, September 20, 2011

How To Crop Images in Java Using JAI

Here is a sample code snippet of creating an application in Java that will crop images using JAI.

/**
Start
**/

RenderedOp image;
BufferedOutputStream output = null;

try{

//Change the value of the phrase in red to the path of the file
//that you want the crop
image = JAI.create("fileload", "/home/cgabisan/Desktop/Strat1.png");


//Origin point where you want to start cropping
Point p = new Point(150, 150);
//The size of the area that you want to crop
Dimension d = new Dimension(90, 70);
Rectangle r = new Rectangle(p,d);

ParameterBlock pb = new ParameterBlock();
pb.addSource(image);

pb.add((float)r.getX());
pb.add((float)r.getY());
pb.add((float)r.getWidth());
pb.add((float)r.getHeight());

//Creates the cropped area
image = JAI.create("crop", pb);

//Change the value in the File constructor with the filename and path
//that you want the cropped image to be save
File file = new File("/home/cgabisan/Desktop/test2.jpeg");

BufferedImage bufferedImage = image.getAsBufferedImage();
output = new BufferedOutputStream(new FileOutputStream(file));
ImageIO.write(bufferedImage, "JPEG", output);

}catch (Exception e){
e.printStackTrace();
} finally{
try {
output.close();
} catch (IOException e) { 
// TODO Auto-generated catch block
e.printStackTrace();
}
}

/**
End
**/

For the sample file, you may download it here

https://picasaweb.google.com/lh/photo/4DlSroqvQerM8ZZ7yKMyVQ?feat=directlink

1 comment: