Deep copying BufferedImage objects

Originally posted on 2020-11-19

When doing a project with DJL I needed to find a way to deep copy BufferedImages. I was working in a multi-threaded system and I wanted to be extra sure that I had my own copy of the image so it wouldn't get modified elsewhere.

It turns out that it was probably overkill and I could get away with a simpler solution but since I found a way to deep copy images reliably I wanted to store it somewhere. Here it is, enjoy!

private static BufferedImage deepCopy(BufferedImage bufferedImage) {
    ColorModel colorModel = bufferedImage.getColorModel();
    boolean isAlphaPremultiplied = colorModel.isAlphaPremultiplied();
    WritableRaster raster = bufferedImage.copyData(null);
    return new BufferedImage(colorModel, raster, isAlphaPremultiplied, null);
}