Resize Stack of Images in imagePlus

Tags: #<Tag:0x00007fd543060868> #<Tag:0x00007fd5430606b0> #<Tag:0x00007fd5430602a0>


I am trying to resize the all the slices of imageplus but i am not able to achieve

public static ImagePlus cropAndResize(ImagePlus originalImage, int targetWidth, int targetHeight)      throws Exception{
	//ImageProcessor ip = imp.getProcessor();
	ImageStack classStack = new ImageStack(targetWidth, targetHeight);
	for (int i=1;i<originalImage.getStackSize();i++)
		ImageProcessor ip = originalImage.getStack().getProcessor(i);
		int cropX = ip.getWidth() / 2;
		    int cropY = ip.getHeight() / 2;
		    ip.setRoi(cropX, cropY, targetWidth, targetHeight);
		    ImageProcessor cropped = ip.crop();
		    BufferedImage croppedImage = ip.getBufferedImage();
		System.out.println(ip.getWidth()+" "+ip.getHeight()+" "+classStack.getWidth()+" "+classStack.getHeight());    
	ImagePlus CI= new ImagePlus("CI", classStack);
	return CI;

public static void main(String[] args) throws Exception {
	// TODO Auto-generated method stub
	String path="/home/mg/Downloads/tifs/image.tif";
	ImagePlus imp = new Opener().openImage(path);
	//System.out.println(imp.getWidth()+ " "+Math.min(imp.getWidth(), imp.getHeight()));
	imp =cropAndResize(imp,50,50);;

I am trying to resize the image, suppose i have ImagePlus image which contains 30 slices now i want to change the size of all the slices, like earlier 512512 to 100100 so i try above but it gives me error
Exception in thread “main” java.lang.IllegalArgumentException: ImageStack.addSlice(): dimensions do not match
i don’t know why
ip.resize(targetWidth,targetHeight); doesn’t change the size.


Dear @M_G,

Could please give a detailed description of what you are expecting that (incomplete!) snippet to do and what your issue is?

In general, please post a minimal, complete, verifiable example that reproduces your issue. Also, you shouldn’t use references to local files but use URLs to sample files instead.



updated my question.


Have a look at the javadoc:

Returns a new ImageProcessor containing a scaled copy of this image or ROI.

It does not resize the ImageProcessor inplace, but returns a scaled copy. So you should maybe write:

resized = ip.resize(targetWidth,targetHeight);

I think your code is way too complicated to achieve what you want, but unfortunately it’s unclear to me what you actually want to achieve. Why do you get a BufferedImage? I see no place where it’s being used. Do you want to crop and resize, as the name suggests? Then, what determines the crop size, and what the resizing target dimensions?