Cropping An Image In Java [Sample/Tutorial With Source Code]

Cropping refers to the removal of the outer parts of an image to improve framing, accentuate subject matter or change aspect ratio. Depending on the application, this may be performed on a physical photograph, artwork or film footage, or achieved digitally using image editing software. The term is common to the film, broadcasting, photographic, graphic design and printing industries.

In the printing, graphic design and photography industries, cropping refers to removing unwanted areas from a photographic or illustrated image. One of the most basic photo manipulation processes, it is performed in order to remove an unwanted subject or irrelevant detail from a photo, change its aspect ratio, or to improve the overall composition. In telephoto photography, most commonly in bird photography, an image is cropped to magnify the primary subject and further reduce the angle of view when a lens of sufficient focal length to achieve the desired magnification directly is not available. It is considered one of the few editing actions permissible in modern photojournalism along with tonal balance, colour correction and sharpening. A crop made from the top and bottom of a photograph may produce an aspect which mimics the panoramic format (in photography) and the widescreen format in cinematography and broadcasting. Both of these formats are not cropped as such, rather the product of highly specialised optical configuration and camera design. [Wikipedia]

The following picture shows the cropping are lying within the image.

The following image shows portions of cropping area lying outside the original image

The following program written in java show how image cropping can be done easily. The program takes an image and the cropping parameters as input.
Then it determines if the cropping area lies within the image or not. In case a cropping area in portion or fully lies outside the main image co-ordinates, the program adjusts the crop area.

The parameters used in the cropping are:
— Height of the cropping rectangle.
— Width of the cropping rectangle.
— X Co-ordinate of the start point of the cropping rectangle.
— Y Co-ordinate of the start point of the cropping rectangle.

The program also takes care of the negative co-ordinates supplied for the crop area rectangle.

Finally the program crops the input image and saves a copy of the cropped image.

You can find more comments int the java program itself.

package com.kushal.graphics;
/**
 * @Author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified On 2009-10-08
 *
 * This utility crops an image with the provided
 * crop parameters (crop rectangle dimension and
 * rectangle start co-ordinates)
 */
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.image.RasterFormatException;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ImageCropper {

static Rectangle clip;

public static void main(String args[]) throws Exception {
String inputFileLocation = "C:/temp/myImage02.jpg";
String outputFileLocation = "C:/temp/myImage-cropped.jpg";

System.out.println("Reading Original File : " + inputFileLocation);

BufferedImage originalImage = readImage(inputFileLocation);

/**
* Image Cropping Parameters
*/
int cropHeight = 150;
int cropWidth = 150;
int cropStartX = 50;
int cropStartY = 50;

BufferedImage processedImage = cropMyImage(originalImage, cropWidth,
cropHeight, cropStartX, cropStartY);

System.out.println("Writing the cropped image to: "
+ outputFileLocation);
writeImage(processedImage, outputFileLocation, "jpg");
System.out.println("...Done");
}

public static BufferedImage cropMyImage(BufferedImage img, int cropWidth,
int cropHeight, int cropStartX, int cropStartY) throws Exception {
BufferedImage clipped = null;
Dimension size = new Dimension(cropWidth, cropHeight);

createClip(img, size, cropStartX, cropStartY);

try {
int w = clip.width;
int h = clip.height;

System.out.println("Crop Width " + w);
System.out.println("Crop Height " + h);
System.out.println("Crop Location " + "(" + clip.x + "," + clip.y
+ ")");

clipped = img.getSubimage(clip.x, clip.y, w, h);

System.out.println("Image Cropped. New Image Dimension: "
+ clipped.getWidth() + "w X " + clipped.getHeight() + "h");
} catch (RasterFormatException rfe) {
System.out.println("Raster format error: " + rfe.getMessage());
return null;
}
return clipped;
}

/**
* This method crops an original image to the crop parameters provided.
*
* If the crop rectangle lies outside the rectangle (even if partially),
* adjusts the rectangle to be included within the image area.
*
* @param img = Original Image To Be Cropped
* @param size = Crop area rectangle
* @param clipX = Starting X-position of crop area rectangle
* @param clipY = Strating Y-position of crop area rectangle
* @throws Exception
*/
private static void createClip(BufferedImage img, Dimension size,
int clipX, int clipY) throws Exception {
/**
* Some times clip area might lie outside the original image,
* fully or partially. In such cases, this program will adjust
* the crop area to fit within the original image.
*
* isClipAreaAdjusted flas is usded to denote if there was any
* adjustment made.
*/
boolean isClipAreaAdjusted = false;

/**Checking for negative X Co-ordinate**/
if (clipX < 0) {
clipX = 0;
isClipAreaAdjusted = true;
}
/**Checking for negative Y Co-ordinate**/
if (clipY < 0) {
clipY = 0;
isClipAreaAdjusted = true;
}

/**Checking if the clip area lies outside the rectangle**/
if ((size.width + clipX) <= img.getWidth()
&& (size.height + clipY) <= img.getHeight()) {

/**
* Setting up a clip rectangle when clip area
* lies within the image.
*/

clip = new Rectangle(size);
clip.x = clipX;
clip.y = clipY;
} else {

/**
* Checking if the width of the clip area lies outside the image.
* If so, making the image width boundary as the clip width.
*/
if ((size.width + clipX) > img.getWidth())
size.width = img.getWidth() - clipX;

/**
* Checking if the height of the clip area lies outside the image.
* If so, making the image height boundary as the clip height.
*/
if ((size.height + clipY) > img.getHeight())
size.height = img.getHeight() - clipY;

/**Setting up the clip are based on our clip area size adjustment**/
clip = new Rectangle(size);
clip.x = clipX;
clip.y = clipY;

isClipAreaAdjusted = true;

}
if (isClipAreaAdjusted)
System.out.println("Crop Area Lied Outside The Image."
+ " Adjusted The Clip Rectanglen");
}

/**
* This method reads an image from the file
*
* @param fileLocation -- >
*            eg. "C:/testImage.jpg"
* @return BufferedImage of the file read
*/
public static BufferedImage readImage(String fileLocation) {
BufferedImage img = null;
try {
img = ImageIO.read(new File(fileLocation));
System.out.println("Image Read. Image Dimension: " + img.getWidth()
+ "w X " + img.getHeight() + "h");
} catch (IOException e) {
e.printStackTrace();
}
return img;
}

/**
* This method writes a buffered image to a file
*
* @param img -- > BufferedImage
* @param fileLocation --> e.g. "C:/testImage.jpg"
* @param extension --> e.g. "jpg","gif","png"
*/
public static void writeImage(BufferedImage img, String fileLocation,
String extension) {
try {
BufferedImage bi = img;
File outputfile = new File(fileLocation);
ImageIO.write(bi, extension, outputfile);
} catch (IOException e) {
e.printStackTrace();
}
}

/*
* SANJAAL CORPS MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE
* SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SANJAAL CORPS SHALL NOT BE
* LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
* MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
*
* THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE
* CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE
* PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT
* NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE
* SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE
* SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE
* PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). SANJAAL CORPS
* SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR
* HIGH RISK ACTIVITIES.
*/

}

Here is the output of this program:

Reading Original File : C:/temp/myImage02.jpg
Image Read. Image Dimension: 200w X 370h
Crop Width 150
Crop Height 150
Crop Location (50,50)
Image Cropped. New Image Dimension: 150w X 150h
Writing the cropped image to: C:/temp/myImage-cropped.jpg
...Done

Here is the original Picture:

Here is the picture cropped by the program above.

Finding Java Image Pixels Information – ARGB (Alpha, Red, Green Blue)

In digital imaging, a pixel(or picture element) is the smallest item of information in an image. Pixels are normally arranged in a 2-dimensional grid, and are often represented using dots or squares. Each pixel is a sample of an original image, where more samples typically provide more-accurate representations of the original. The intensity of each pixel is variable; in color systems, each pixel has typically three or four components such as red, green, and blue, or cyan, magenta, yellow, and black.

The word pixel is based on a contraction of pix (“pictures”) and el (for “element”); similar formations with el for “element” include the words: voxel and texel. [Wikipedia]

In java 2D images, pixels are arranged in 2 dimensional array. If you take an image of dimension 200×300, there will be a total of 60,000 pixels. Each pixel is represented by a 32 bit integer. 32bit (4Bytes) represent 4 different color information. These color information, called ARGB, stand for Alpha, Red, Green and Blue. Each byte out of 4 Bytes of every pixel represents one of these color information.

In the following tutorial, you will learn

  • How to read image from filesystem
  • How to calculate the image height and width
  • How to loop through each pixel and get pixel info
  • Get alpha (transparency) value from the pixel
  • Get Color info (red, green and blue) from the pixel
  • How to do bit manipulation on an integer

package com.kushal.graphics;

/**
 * @Author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified On: 2009-10-21
 *
 * PrintImageARGBPixels.java
 * Reads an image and prints out it's color and alpha
 * information of individual pixels [Alpha, Red, Green Blue]
 */
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class PrintImageARGBPixels {

	public static void main(String args[]) {
		/**
		 * Read a sample image from the filesystem
		 */
		BufferedImage image = readImage("c:/temp/generalImage.jpg");

		/**
		 * Call the method that prints out ARGB color Information.
		 * ARGB = Alpha, Red, Green and Blue
		 */
		printAllARGBDetails(image);
	}

	public static void printAllARGBDetails(BufferedImage image) {
		int width = image.getWidth();
		int height = image.getHeight();
		System.out.println("Image Dimension: Height-" + height + ", Width-"
				+ width);
		System.out.println("Total Pixels: " + (height * width));
		for (int i = 0; i < width; i++) {
			for (int j = 0; j < height; j++) {

				int pixel = image.getRGB(i, j);
				System.out.println("Pixel Location(" + i + "," + j + ")- ["
						+ getARGBPixelData(pixel) + "]");
			}
		}
	}

	/**
	 * Image Pixels are Arrays of Integers [32 bits/4Bytes]
	 * Consider a 32 pixel as 11111111-00110011-00111110-00011110
	 *
	 * First Byte From Left [11111111]= Alpha
	 * Second Byte From Left[00110011]= Red
	 * Third Byte From Left [00111110]= Green
	 * Fourth Byte From Left[00011110]= Blue
	 *
	 * The following method will do a proper bit shift and
	 * logical AND operation to extract the correct values
	 * of different color/alpha components.
	 *
	 */
	public static String getARGBPixelData(int pixel) {
		String pixelARGBData = "";
		/**
		 * Shift all pixels 24 bits to the right.
		 * Do a logical and with 0x000000FF
		 * i.e. 0000 0000 0000 0000 0000 0000 1111 1111
		 * You will get the alpha value for the pixel
		 */
		int alpha = (pixel >> 24) & 0x000000FF;

		/**
		 * Shift all pixels 16 bits to the right.
		 * Do a logical and with 0x000000FF
		 * i.e. 0000 0000 0000 0000 0000 0000 1111 1111
		 * You will get the red value for the pixel
		 */

		int red = (pixel >> 16) & 0x000000FF;

		/**
		 * Shift all pixels 8 bits to the right.
		 * Do a logical and with 0x000000FF
		 * i.e. 0000 0000 0000 0000 0000 0000 1111 1111
		 * You will get the green value for the pixel
		 */
		int green = (pixel >>8 ) & 0x000000FF;

		/**
		 * Dont do any shift.
		 * Do a logical and with 0x000000FF
		 * i.e. 0000 0000 0000 0000 0000 0000 1111 1111
		 * You will get the blue value for the pixel
		 */
		int blue = (pixel) & 0x000000FF;

		pixelARGBData = "Alpha: " + alpha + ", " + "Red: " + red + ", "
				+ "Green: " + green + ", " + "Blue: " + blue;

		return pixelARGBData;
	}

	/**
	 * This method reads an image from the file
	 * @param fileLocation -- > eg. "C:/testImage.jpg"
	 * @return BufferedImage of the file read
	 */
	public static BufferedImage readImage(String fileLocation) {
		BufferedImage img = null;
		try {
			img = ImageIO.read(new File(fileLocation));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return img;
	}

	/*
	 * SANJAAL CORPS MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
	 * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
	 * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
	 * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SANJAAL CORPS SHALL NOT BE LIABLE FOR
	 * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
	 * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
	 *
	 * THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE
	 * CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE
	 * PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT
	 * NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE
	 * SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE
	 * SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE
	 * PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). SANJAAL CORPS
	 * SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR
	 * HIGH RISK ACTIVITIES.
	 */
}

Sample Image Used In This Program (You can use any of your own).

Output of this program on a sample Image:
Note that I have shortened the output by removing many lines from in between. This is because I took a 122×122 image and there were a total of 14884 pixel info printed on the screen.

The complete  output file is available here.

Image Dimension: Height-122, Width-122
Total Pixels: 14884
Pixel Location(0,0)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(0,1)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(0,2)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(0,3)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(0,4)- [Alpha: 255, Red: 255, Green: 254, Blue: 255]
Pixel Location(0,5)- [Alpha: 255, Red: 255, Green: 254, Blue: 255]
Pixel Location(0,6)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(0,7)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(0,8)- [Alpha: 255, Red: 254, Green: 255, Blue: 255]
Pixel Location(0,9)- [Alpha: 255, Red: 254, Green: 255, Blue: 255]
Pixel Location(0,10)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(0,11)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(0,12)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(0,13)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(0,14)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(0,15)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(0,16)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
.
.
.
Pixel Location(90,26)- [Alpha: 255, Red: 216, Green: 217, Blue: 219]
Pixel Location(90,27)- [Alpha: 255, Red: 219, Green: 215, Blue: 216]
Pixel Location(90,28)- [Alpha: 255, Red: 216, Green: 216, Blue: 216]
Pixel Location(90,29)- [Alpha: 255, Red: 210, Green: 214, Blue: 213]
Pixel Location(90,30)- [Alpha: 255, Red: 206, Green: 210, Blue: 209]
Pixel Location(90,31)- [Alpha: 255, Red: 219, Green: 212, Blue: 202]
Pixel Location(90,32)- [Alpha: 255, Red: 235, Green: 205, Blue: 179]
Pixel Location(90,33)- [Alpha: 255, Red: 221, Green: 167, Blue: 121]
Pixel Location(90,34)- [Alpha: 255, Red: 213, Green: 132, Blue: 66]
Pixel Location(90,35)- [Alpha: 255, Red: 220, Green: 130, Blue: 52]
Pixel Location(90,36)- [Alpha: 255, Red: 212, Green: 133, Blue: 56]
Pixel Location(90,37)- [Alpha: 255, Red: 196, Green: 139, Blue: 72]
Pixel Location(90,38)- [Alpha: 255, Red: 185, Green: 161, Blue: 115]
Pixel Location(90,39)- [Alpha: 255, Red: 206, Green: 203, Blue: 160]
Pixel Location(90,40)- [Alpha: 255, Red: 207, Green: 213, Blue: 153]
Pixel Location(90,41)- [Alpha: 255, Red: 174, Green: 189, Blue: 120]
Pixel Location(90,42)- [Alpha: 255, Red: 160, Green: 183, Blue: 113]
Pixel Location(90,43)- [Alpha: 255, Red: 124, Green: 155, Blue: 114]
.
.
.
Pixel Location(121,105)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(121,106)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(121,107)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(121,108)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(121,109)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(121,110)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(121,111)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(121,112)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(121,113)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(121,114)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(121,115)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(121,116)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(121,117)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(121,118)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(121,119)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(121,120)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(121,121)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]