问题

我有一个对象,其中有许多bufferedimages,我想创建一个新的对象将所有bufferedimages复制到新对象,但这些新图像可能会被更改,我不希望通过更改原始对象图像来改变新物体图像。

明白了吗?

这可能吗,有人可以建议一个好方法吗?我已经想到了getSubImage,但是在某处读取了对子图像的任何更改都被重新选回到父图像。

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


#1 热门回答(154 赞)

像这样的东西?

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

#2 热门回答(38 赞)

我这样做:

public static BufferedImage copyImage(BufferedImage source){
    BufferedImage b = new BufferedImage(source.getWidth(), source.getHeight(), source.getType());
    Graphics g = b.getGraphics();
    g.drawImage(source, 0, 0, null);
    g.dispose();
    return b;
}

它工作得很好,使用起来很简单。


#3 热门回答(16 赞)

应用于子图像时,前面提到的过程失败。这是一个更完整的解决方案:

public static BufferedImage deepCopy(BufferedImage bi) {
    ColorModel cm = bi.getColorModel();
    boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
    WritableRaster raster = bi.copyData(bi.getRaster().createCompatibleWritableRaster());
    return new BufferedImage(cm, raster, isAlphaPremultiplied, null);
}

原文链接