
// CropAndResize.java
// Andrew Davison, ad@coe.psu.ac.th, April 2023

/* Proportionately crop the image to make a square 
   and save a resized thumbnail version of 100x100 pixels.

   Usage:
     > compile CropAndResize.java
     > run CropAndResize <fnm>
   e.g.
     > run CropAndResize squares.png
     > run CropAndResize frankenburg-1918.png
*/

import java.awt.*;

import ij.*;
import ij.process.*;


public class CropAndResize
{

  public static void main(String[]args)
  {
    if (args.length != 1) {
      System.out.println("Usage: run cropAndResize <fnm>");
      return;
    }
    ImagePlus imp = new ImagePlus(args[0]);
    imp.show();
    
    // calculate crop dimensions
    int width = imp.getWidth();
    int height = imp.getHeight();
    
    int cropWidth = 0;
    int cropHeight = 0;
    if (width > height) {
      cropWidth = height;
      cropHeight = height;
    } 
    else {
      cropWidth = width;
      cropHeight = width;
    }
    
    int x = -1;
    int y = -1;
    if (width == height) {
      x = 0;
      y = 0;
    } 
    else if (width > height) {
      x = (width - height)/2;
      y = 0;
    } 
    else if (width < height) {
      x = 0;
      y = (height - width)/2;
    }
     
    System.out.println("Image x,y: " + x + ", " + y );

    System.out.println("(w, h): " + "(" + imp.getWidth() +
                             ", " + imp.getHeight() + ")");

    System.out.println("Crop (w, h): " + "(" + cropWidth +
                             ", " + cropHeight + ")");


    imp.setRoi(x, y, cropWidth, cropHeight);
    ImagePlus impCrop = imp.crop();
    ImagePlus impSized = impCrop.resize(100, 100, "bilinear");
    impSized.show();
    
    String nm = ImageUtils.getName(args[0]);

    System.out.println("Saving thumbnail to " + nm + "Thumb.png");
    IJ.saveAs(impCrop, "png", nm + "Thumb.png");

    ImageUtils.waitGone(impSized.getTitle());
    System.exit(0);
  }  // end of main()

} // end of CropAndResize class