Here you can find the source of trimImageVerticallyHelper(BufferedImage image, int maxToTrim)
Parameter | Description |
---|---|
image | image to be trimmed |
maxToTrim | the maximum whitespace that can be trimmed off this image |
private static BufferedImage trimImageVerticallyHelper(BufferedImage image, int maxToTrim)
//package com.java2s; //License from project: Open Source License import java.awt.image.BufferedImage; import java.awt.image.PixelGrabber; public class Main { /**/*from w w w .j a va 2s. c o m*/ * A helper method which actually trims an image. This method trims rows. * * @param image image to be trimmed * @param maxToTrim the maximum whitespace that can be trimmed off this image * @return a trimmed image */ private static BufferedImage trimImageVerticallyHelper(BufferedImage image, int maxToTrim) { try { /* Create an one dimensional pixel array to store the image pixels */ int[] pix = new int[image.getWidth() * image.getHeight()]; PixelGrabber grab = new PixelGrabber(image, 0, 0, image.getWidth(), image.getHeight(), pix, 0, image.getWidth()); if (!grab.grabPixels()) return image; int lastClearRow = 0; int x; int y = 1; /* Image is transparent*/ int alpha = 0; /* Image is white (RGB) */ int red = 255; int green = 255; int blue = 255; /* Iterate over the height of the image */ while (y < image.getHeight()) { /* Reset the width counter */ x = 0; /* Check whether the image is transparent or white if yes perform the trim operation until the entire width of the image */ while (x < image.getWidth() && ((alpha == 0) || (red == 255 && green == 255 && blue == 255))) { int i = y * image.getWidth() + x; int pixel = pix[i]; alpha = (pixel >> 24) & 0xff; red = (pixel >> 16) & 0xff; green = (pixel >> 8) & 0xff; blue = (pixel) & 0xff; x++; } /* Executed only when the entire row has been checked*/ if (x == image.getWidth()) lastClearRow = y; y++; } int trimmable = Math.min(lastClearRow, maxToTrim); /* Trim the image vertically */ return image.getSubimage(0, trimmable, image.getWidth(), image.getHeight() - trimmable); } catch (InterruptedException e) { return image; } } }