Java BufferedImage Deep Copy deepCopy(BufferedImage source)

Here you can find the source of deepCopy(BufferedImage source)

Description

Returns a copy of a BufferedImage object.

License

Open Source License

Parameter

Parameter Description
source the image to copy

Declaration

public static BufferedImage deepCopy(BufferedImage source) 

Method Source Code

//package com.java2s;
/*/* w  w w. ja v a 2s .c  o m*/
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.awt.Graphics;

import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;

public class Main {
    /**
     * Returns a copy of a BufferedImage object.
     * <br><br>
     * Taken from
     * <a href="http://stackoverflow.com/a/19327237" target="_blank">here</a>
     * (CC BY-SA 3.0).
     * and from 
     * <a href="http://stackoverflow.com/a/3514297" target="_blank">here</a>
     * (CC BY-SA 3.0).
     *
     * @param source   the image to copy
     */
    public static BufferedImage deepCopy(BufferedImage source) {
        BufferedImage result;
        Graphics g;
        ColorModel cm;
        boolean isAlphaPremultiplied;
        WritableRaster raster;

        if (source.getType() == BufferedImage.TYPE_CUSTOM) {
            cm = source.getColorModel();
            isAlphaPremultiplied = cm.isAlphaPremultiplied();
            raster = source.copyData(null);
            result = new BufferedImage(cm, raster, isAlphaPremultiplied, null);
        } else {
            result = new BufferedImage(source.getWidth(), source.getHeight(), source.getType());
            g = result.getGraphics();
            g.drawImage(source, 0, 0, null);
            g.dispose();
        }

        return result;
    }
}

Related

  1. deepCopy(BufferedImage bi)
  2. deepCopy(BufferedImage bi)
  3. deepCopy(BufferedImage image)
  4. deepCopy(BufferedImage image)