How to clone a java.awt.BufferedImage ?

O

oliv

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
 
T

Tom Hawtin

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 ?
public class MyBufferedImage extends BufferedImage implements
Cloneable {

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
 
A

a24900

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).

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);
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top