Java BufferedImage Trim trim(BufferedImage img)

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

Description

Removes the white borders of a BufferedImage .

License

Open Source License

Parameter

Parameter Description
img Input image

Return

The input image without white borders

Declaration

public static BufferedImage trim(BufferedImage img) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2016 Pablo Pavon-Marino.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 *
 * Contributors://www.  j  a va 2  s .  c om
 *     Pablo Pavon-Marino - Jose-Luis Izquierdo-Zaragoza, up to version 0.3.1
 *     Pablo Pavon-Marino - from version 0.4.0 onwards
 ******************************************************************************/

import java.awt.Color;

import java.awt.Graphics;

import java.awt.image.BufferedImage;

public class Main {
    /**
     * Removes the white borders of a {@code BufferedImage}.
     *
     * @param img Input image
     * @return The input image without white borders
     */
    public static BufferedImage trim(BufferedImage img) {
        final int width = img.getWidth();
        final int height = img.getHeight();
        if (width == 0 || height == 0)
            return img;

        int topY = Integer.MAX_VALUE;
        int topX = Integer.MAX_VALUE;
        int bottomY = Integer.MIN_VALUE;
        int bottomX = Integer.MIN_VALUE;
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                if (img.getRGB(x, y) != Color.WHITE.getRGB()) {
                    if (x < topX)
                        topX = x;
                    if (y < topY)
                        topY = y;
                    if (x > bottomX)
                        bottomX = x;
                    if (y > bottomY)
                        bottomY = y;
                }
            }
        }

        bottomX = Math.min(bottomX + 1, width - 1);
        bottomY = Math.min(bottomY + 1, height - 1);

        BufferedImage newImg = new BufferedImage(bottomX - topX + 1, bottomY - topY + 1,
                BufferedImage.TYPE_INT_ARGB);
        Graphics g = newImg.createGraphics();
        g.drawImage(img, 0, 0, newImg.getWidth(), newImg.getHeight(), topX, topY, bottomX, bottomY, null);
        g.dispose();

        return newImg;
    }
}

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(final BufferedImage img)
  6. trimAroundCenter(BufferedImage img, Point center, Color bgColor)
  7. trimImage(BufferedImage image)
  8. trimImage(BufferedImage imageToTrim)