How to clone a java.awt.BufferedImage?
private BufferedImage originalImage;
private BufferedImage copiedImage;
public MyClass(BufferedImage image) {
originalImage = image;
copiedImage= originalImage .clone();
}
The issue is that BufferedImage.clone does not exist.
When I just do this:
copiedImage= originalImage;
then when I modify the copied image I am also modifying the orriginal.
I know I am dealing with a pointer with the BufferedImage, but I am not sure how to get around it at this point.
Thanks,
Justus
[554 byte] By [
JBrakea] at [2007-11-27 2:30:14]

You can't clone, you have to roll up your sleeves and copy. There must be
a hundred ways to do that -- here's a straightforward way:
import java.awt.*;
import java.awt.image.*;
public class ImageCopy {
public static BufferedImage copy(BufferedImage im) {
int w = im.getWidth();
int h = im.getHeight();
int type = im.getType();
if (type == BufferedImage.TYPE_CUSTOM) {
System.out.println("note: not preserving type");
type = im.getColorModel().hasAlpha() ?
BufferedImage.TYPE_INT_ARGB :
BufferedImage.TYPE_INT_RGB;
}
BufferedImage result = new BufferedImage(w, h, type);
Graphics2D g = result.createGraphics();
g.drawRenderedImage(im, null);
g.dispose();
return result;
}
}