Java BufferedImage Trim trim(final BufferedImage img)

Here you can find the source of trim(final BufferedImage img)

Description

Trims white margins from a BufferedImage .

License

Open Source License

Parameter

Parameter Description
img image to trim

Return

trimmed image

Declaration

public static BufferedImage trim(final BufferedImage img) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.awt.Color;

import java.awt.image.BufferedImage;

public class Main {
    /**//from  www  . jav a2  s.  c  om
     * Trims white margins from a {@link BufferedImage}.
     *
     * @param img
     *            image to trim
     * @return trimmed image
     */
    public static BufferedImage trim(final BufferedImage img) {

        int xMin = -1, xMax = -1, yMin = -1, yMax = -1;

        final int w = img.getWidth(), h = img.getHeight();

        // from top
        x1: for (int x = 0; x < w; x++) {
            for (int y = 0; y < h; y++) {
                if (!isWhite(img, x, y)) {
                    xMin = x;
                    break x1;
                }
            }
        }

        // from bottom
        x2: for (int x = w; x-- > 0;) {
            for (int y = 0; y < h; y++) {
                if (!isWhite(img, x, y)) {
                    xMax = x;
                    break x2;
                }
            }
        }

        // from left
        y1: for (int y = 0; y < h; y++) {
            for (int x = xMin; x <= xMax; x++) {
                if (!isWhite(img, x, y)) {
                    yMin = y;
                    break y1;
                }
            }
        }

        // from right
        y2: for (int y = h; y-- > 0;) {
            for (int x = xMin; x <= xMax; x++) {
                if (!isWhite(img, x, y)) {
                    yMax = y;
                    break y2;
                }
            }
        }

        return img.getSubimage(xMin, yMin, xMax - xMin + 1, yMax - yMin + 1);
    }

    /**
     * Checks whether the pixel on the given position in the image is white.
     *
     * @param img image
     * @param x x position
     * @param y y position
     * @return {@code true}, if the pixel is white, {@code false} otherwise
     */
    private static boolean isWhite(final BufferedImage img, final int x, final int y) {
        final int rgb = img.getRGB(x, y), trans = Color.BLACK.getRGB();
        return (rgb & trans) == 0 || (rgb | trans) == Color.WHITE.getRGB();
    }
}

Related

  1. trim(BufferedImage image)
  2. trim(BufferedImage image)
  3. trim(BufferedImage image, int trimTop, int trimLeft, int trimBottom, int trimRight)
  4. trim(BufferedImage image, Rectangle trimRect)
  5. trim(BufferedImage img)
  6. trimAroundCenter(BufferedImage img, Point center, Color bgColor)
  7. trimImage(BufferedImage image)
  8. trimImage(BufferedImage imageToTrim)
  9. trimImageHorizontally(BufferedImage image, boolean trimFromEnd, int maxToTrim)