Trims the transparent pixels from the given BufferedImage (returns a sub-image). - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage Pixel

Description

Trims the transparent pixels from the given BufferedImage (returns a sub-image).

Demo Code

/*/*from  w  ww  .  java 2 s.  c o m*/
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//package com.java2s;

import java.awt.image.BufferedImage;

import java.awt.image.Raster;

public class Main {
    /**
     * Trims the transparent pixels from the given {@link BufferedImage} (returns a sub-image).
     *
     * @param source The source image.
     * @return A new, trimmed image, or the source image if no trim is performed.
     */
    public static BufferedImage trimmedImage(BufferedImage source) {
        final int minAlpha = 1;
        final int srcWidth = source.getWidth();
        final int srcHeight = source.getHeight();
        Raster raster = source.getRaster();
        int l = srcWidth, t = srcHeight, r = 0, b = 0;
        int alpha, x, y;
        int[] pixel = new int[4];
        for (y = 0; y < srcHeight; y++) {
            for (x = 0; x < srcWidth; x++) {
                raster.getPixel(x, y, pixel);
                alpha = pixel[3];
                if (alpha >= minAlpha) {
                    l = Math.min(x, l);
                    t = Math.min(y, t);
                    r = Math.max(x, r);
                    b = Math.max(y, b);
                }
            }
        }
        if (l > r || t > b) {
            // No pixels, couldn't trim
            return source;
        }
        return source.getSubimage(l, t, r - l + 1, b - t + 1);
    }
}

Related Tutorials