remove BufferedImage Alpha Channel - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage Color

Description

remove BufferedImage Alpha Channel

Demo Code

/*//from ww  w  . j a va  2s . c  o m
 * Copyright 2000-2013 Enonic AS
 * http://www.enonic.com/license
 */
//package com.java2s;
import java.awt.Color;

import java.awt.Graphics2D;

import java.awt.image.BufferedImage;

public class Main {
    public static BufferedImage removeAlphaChannel(BufferedImage img,
            int color) {
        if (!img.getColorModel().hasAlpha()) {
            return img;
        }

        BufferedImage target = createImage(img, false);
        Graphics2D g = target.createGraphics();
        g.setColor(new Color(color, false));
        g.fillRect(0, 0, img.getWidth(), img.getHeight());
        g.drawImage(img, 0, 0, null);
        g.dispose();

        return target;
    }

    public static BufferedImage createImage(BufferedImage src,
            boolean hasAlpha) {

        return createImage(src.getWidth(), src.getHeight(), hasAlpha);
    }

    public static BufferedImage createImage(int width, int height,
            boolean hasAlpha) {
        return new BufferedImage(width, height,
                hasAlpha ? BufferedImage.TYPE_INT_ARGB
                        : BufferedImage.TYPE_INT_RGB);
    }
}

Related Tutorials