Skip to content

Instantly share code, notes, and snippets.

@tc
Created September 14, 2011 20:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tc/1217766 to your computer and use it in GitHub Desktop.
Save tc/1217766 to your computer and use it in GitHub Desktop.
resize and crop using imagej -java version
package imagej;
import ij.*;
import ij.io.*;
import ij.process.*;
import java.io.*;
import javax.imageio.*;
import javax.imageio.stream.*;
import java.awt.image.BufferedImage;
public class AppTest{
public static void main(String [] args) throws Exception{
String url = "http://imagej.nih.gov/ij/images/lena-std.tif";
ImagePlus imp = IJ.openImage(url);
cropAndResize(imp, 400, 100);
}
public static void cropAndResize(ImagePlus imp, int targetWidth, int targetHeight) throws Exception{
ImageProcessor ip = imp.getProcessor();
System.out.println("size1: "+ip.getWidth()+"x"+ip.getHeight());
ip.setInterpolationMethod(ImageProcessor.BILINEAR);
ip = ip.resize(targetWidth * 2, targetHeight * 2);
System.out.println("size2: "+ip.getWidth()+"x"+ip.getHeight());
int cropX = ip.getWidth() / 2;
int cropY = ip.getHeight() / 2;
ip.setRoi(cropX, cropY, targetWidth, targetHeight);
ip = ip.crop();
System.out.println("size3: "+ip.getWidth()+"x"+ip.getHeight());
BufferedImage croppedImage = ip.getBufferedImage();
System.out.println("size4: "+ip.getWidth()+"x"+ip.getHeight());
new ImagePlus("croppedImage", croppedImage).show();
ImageIO.write(croppedImage, "jpg", new File("cropped.jpg"));
}
}
@16Jam
Copy link

16Jam commented Aug 24, 2016

Hi, Do you have full code for the above? I would like to see the class for ImageProcessor & ImagePlus?
Thanks,
Jam

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment