如何克隆 BufferedImage

2022-01-20 00:00:00 复制 clone java bufferedimage

我有一个包含许多缓冲图像的对象,我想创建一个新对象,将所有缓冲图像复制到新对象中,但是这些新图像可能会被更改,我不希望原始对象图像被更改通过更改新对象图像.

I have an object which has many bufferedimages in it, I want to create a new object copying all the bufferedimages into the new object, but these new images may be altered and i don't want the original object images to be altered by altering the new objects images.

清楚吗?

这是可能的吗?有人可以提出一个好的方法吗?我曾考虑过 getSubImage,但在某处读到,对子图像的任何更改都会被反射回父图像.

Is this possible to do and can anyone suggest a good way to do it please? I have thought of getSubImage but read somewhere that any changes to the subimage are relected back to the parent image.

我只是希望能够获得一个全新的、完全独立的 BufferedImage 副本或克隆

I just want to be able to get a fresh entirely separate copy or clone of a BufferedImage

推荐答案

像这样?

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

相关文章