Java BufferedImage Crop adjustRectToFitImage(BufferedImage image, Rectangle cropRect)

Here you can find the source of adjustRectToFitImage(BufferedImage image, Rectangle cropRect)

Description

Adjust the crop rectangle to fit within the image it is cropping.

License

Open Source License

Parameter

Parameter Description
image The image being cropped
cropRect The rectangle defining the cropping area. This may be updated.

Declaration

public static void adjustRectToFitImage(BufferedImage image, Rectangle cropRect) 

Method Source Code

//package com.java2s;
/*//from  w w  w  . j  ava 2 s . c  o  m
 * CoreUtility.java
 * Copyright 2002-2003 (C) B. K. Oxley (binkley)
 * <binkley@alumni.rice.edu>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA
 *
 * Created on Februrary 4th, 2002.
 */

import java.awt.Rectangle;

import java.awt.image.BufferedImage;

public class Main {
    /**
     * Adjust the crop rectangle to fit within the image it is cropping. Also 
     * ensure the area is square.
     * 
     * @param image The image being cropped
     * @param cropRect The rectangle defining the cropping area. This may be updated.
     */
    public static void adjustRectToFitImage(BufferedImage image, Rectangle cropRect) {
        // Make sure the rectangle is not too big
        if (cropRect.width > image.getWidth()) {
            cropRect.width = image.getWidth();
        }
        if (cropRect.height > image.getHeight()) {
            cropRect.height = image.getHeight();
        }

        // Make it square
        int dimension = Math.min(cropRect.width, cropRect.height);
        cropRect.setSize(dimension, dimension);

        // Now adjust the origin point so the box is within the image 
        if ((cropRect.x + cropRect.width) > image.getWidth()) {
            cropRect.x = image.getWidth() - cropRect.width;
        }
        if ((cropRect.y + cropRect.height) > image.getHeight()) {
            cropRect.y = image.getHeight() - cropRect.height;
        }
    }
}

Related

  1. autoCrop(BufferedImage source)
  2. autoCrop(BufferedImage source, double tolerance)
  3. crop(BufferedImage image, Rectangle clip)
  4. crop(BufferedImage input, int x, int y, int width, int height)