How to clone a java.awt.BufferedImage ?

Discussion in 'Java' started by oliv, Mar 11, 2007.

  1. oliv

    oliv Guest

    hi,
    I have to use a function that returns a java.awt.BufferedImage :

    BufferedImage image=function.method(..);

    I want now to clone the "image" instance (different instance but same
    information).

    // of course it does not work because clone method is not public
    BufferedImage clone=(BufferedImage)image.clone();

    What is the fatest way to do that ?

    I tried this:
    public class MyBufferedImage extends BufferedImage implements
    Cloneable {

    /* I don't know how to do the constructor ?? */
    MyBufferedImage() {
    super(null,null,true,null);
    }
    public Object clone() throws CloneNotSupportedException
    {
    return super.clone();
    }
    }

    and I don't know what to do next with this class
    thanks
     
    oliv, Mar 11, 2007
    #1
    1. Advertisements

  2. oliv

    Tom Hawtin Guest

    Cloneable is seriously broken. Shallow copying field for field in a
    class is almost certainly the wrong thing to do for anything more
    complicated than Rectangle.

    A close approximation to clone for BufferedImage is:

    BufferedImage clone = image.getSubimage(
    0, 0, image.getWidth(), image.getHeight()
    );

    That is a shallow clone - it shares image data with the original. Update
    one and the other follows.

    I guess you could create a BufferedImage of the same size, getWraster
    and then copyData on the original. I really don't know the relative
    performance of different ways of using BufferedImage, which probably
    depend upon version of Java, graphics card and drivers anyway.

    Tom Hawtin
     
    Tom Hawtin, Mar 11, 2007
    #2
    1. Advertisements

  3. oliv

    a24900 Guest

    String[] pnames = image.getPropertyNames();
    Hashtable<String, Object> cproperties = new Hashtable<String,
    Object>();
    if(pnames != null) {
    for(int i = 0; i < pnames.length; i++) {
    cproperties.put(pnames, image.getProperty(pnames);
    }
    }
    WritableRaster wr = image.getRaster();
    WritableRaster cwr = wr.createCompatibleWritableRaster();
    cwr.setRect(wr);
    BufferedImage cimage = BufferedImage(
    image.getColorModel(), // should be immutable
    cwr,
    image.isRasterPremultiplied(),
    cproperties);
     
    a24900, Mar 11, 2007
    #3
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.