package com.kodcu.other;

import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * Created by usta on 16.03.2015.
 */
public class TrimWhite {

    public BufferedImage trim(BufferedImage img) {
        int width = getTrimmedWidth(img);
        int height = getTrimmedHeight(img);

        BufferedImage newImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = newImg.createGraphics();
        g.drawImage(img, 0, 0, null);
        g.dispose();
        return newImg;
    }

    private int getTrimmedWidth(BufferedImage img) {
        int height = img.getHeight();
        int width = img.getWidth();
        int trimmedWidth = 0;

        for (int i = 0; i < height; i++) {
            for (int j = width - 1; j >= 0; j--) {
                if (img.getRGB(j, i) != Color.WHITE.getRGB() &&
                        j > trimmedWidth) {
                    trimmedWidth = j;
                    break;
                }
            }
        }

        return trimmedWidth;
    }

    private int getTrimmedHeight(BufferedImage img) {
        int width = img.getWidth();
        int height = img.getHeight();
        int trimmedHeight = 0;

        for (int i = 0; i < width; i++) {
            for (int j = height - 1; j >= 0; j--) {
                if (img.getRGB(i, j) != Color.WHITE.getRGB() &&
                        j > trimmedHeight) {
                    trimmedHeight = j;
                    break;
                }
            }
        }

        return trimmedHeight;
    }

}

@@ -235,16 +235,20 @@
 dth(img)
+ + 5
 ;%0A      
@@ -283,16 +283,20 @@
 ght(img)
+ + 5
 ;%0A%0A     

Add trimmed white space 5px margin