Java BufferedImage Deep Copy deepCopy(BufferedImage bi)

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

Description

Deep clone a BufferedIamge

License

Open Source License

Parameter

Parameter Description
bi Original image

Return

Cloned image

Declaration

public static BufferedImage deepCopy(BufferedImage bi) 

Method Source Code

//package com.java2s;
/* Copyright 2012 Yaqiang Wang,
* yaqiang.wang@gmail.com/* w ww.  j av  a 2s  .  c o  m*/
* 
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at
* your option) any later version.
* 
* This library 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 Lesser
* General Public License for more details.
*/

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

import java.awt.image.WritableRaster;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Main {
    /**
     * Deep clone object
     *
     * @param oldObj Old object
     * @return Cloned object
     * @throws Exception
     */
    public static Object deepCopy(Object oldObj) throws Exception {
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream(); // A
            oos = new ObjectOutputStream(bos); // B
            // serialize and pass the object
            oos.writeObject(oldObj); // C
            oos.flush(); // D
            ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray()); // E
            ois = new ObjectInputStream(bin); // F
            // return the new object
            return ois.readObject(); // G
        } catch (Exception e) {
            System.out.println("Exception in ObjectCloner = " + e);
            throw (e);
        } finally {
            oos.close();
            ois.close();
        }
    }

    /**
     * Deep clone a BufferedIamge
     *
     * @param bi Original image
     * @return Cloned image
     */
    public static BufferedImage deepCopy(BufferedImage bi) {
        ColorModel cm = bi.getColorModel();
        boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
        WritableRaster raster = bi.copyData(null);
        return new BufferedImage(cm, raster, isAlphaPremultiplied, null);
    }
}

Related

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