Here you can find the source of trimImg(BufferedImage img, Color backgroundColor)
public static BufferedImage trimImg(BufferedImage img, Color backgroundColor)
//package com.java2s; //License from project: Open Source License import java.awt.Color; import java.awt.Graphics; import java.awt.image.BufferedImage; public class Main { public static BufferedImage trimImg(BufferedImage img, Color backgroundColor) { // TODO instead of iterating through the columns of image, we can use BINARY SEARCH through columns // and check if column doesn't contain at least 1 non-background colour pixel int imgHeight = img.getHeight(); int imgWidth = img.getWidth(); // TRIM WIDTH - LEFT int startWidth = 0; for (int x = 0; x < imgWidth; x++) { if (startWidth == 0) { for (int y = 0; y < imgHeight; y++) { if (img.getRGB(x, y) != backgroundColor.getRGB()) { startWidth = x;/* www. j a v a 2 s . c o m*/ break; } } } else break; } // TRIM WIDTH - RIGHT int endWidth = 0; for (int x = imgWidth - 1; x >= 0; x--) { if (endWidth == 0) { for (int y = 0; y < imgHeight; y++) { if (img.getRGB(x, y) != backgroundColor.getRGB()) { endWidth = x; break; } } } else break; } int newWidth = endWidth - startWidth; BufferedImage newImg = new BufferedImage(newWidth, imgHeight, BufferedImage.TYPE_INT_RGB); Graphics g = newImg.createGraphics(); g.drawImage(img, 0, 0, newImg.getWidth(), newImg.getHeight(), startWidth, 0, endWidth, imgHeight, null); img = newImg; return img; } }