Java BufferedImage Trim trimImg(BufferedImage img, Color backgroundColor)

Here you can find the source of trimImg(BufferedImage img, Color backgroundColor)

Description

trim Img

License

Open Source License

Declaration

public static BufferedImage trimImg(BufferedImage img, Color backgroundColor) 

Method Source Code


//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;
    }
}

Related

  1. trimAroundCenter(BufferedImage img, Point center, Color bgColor)
  2. trimImage(BufferedImage image)
  3. trimImage(BufferedImage imageToTrim)
  4. trimImageHorizontally(BufferedImage image, boolean trimFromEnd, int maxToTrim)
  5. trimImageVerticallyHelper(BufferedImage image, int maxToTrim)
  6. trimLockdown(BufferedImage Img, int y1)
  7. trimLockup(BufferedImage Img)
  8. trimmedImage(BufferedImage source)
  9. trimWhiteSpace(BufferedImage img)