Java – Cloning a BufferedImage object
This post shows you how to clone or copy a BufferedImage
object in Java. Let’s take a look into the below implementation and example to see how it works.
1. Implementation
Here is the method cloning a BufferedImage
object.
ImageUtils.java
package com.bytenota;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
public class ImageUtils {
public static BufferedImage clone(BufferedImage bufferImage) {
ColorModel colorModel = bufferImage.getColorModel();
WritableRaster raster = bufferImage.copyData(null);
boolean isAlphaPremultiplied = colorModel.isAlphaPremultiplied();
return new BufferedImage(colorModel, raster, isAlphaPremultiplied, null);
}
}
2. Example
In this code example, we test the implemented method above. We simply create a new BufferedImage
object from an image file, clone this object to another by using ImageUtils.clone
method, and finally compare these two objects.
Example.java
package com.bytenota;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Example {
public static void main(String[] args) throws IOException {
// create BufferedImage object from a image file
File imageFile = new File("D:/myfile.jpg");
BufferedImage bufferedImage1 = ImageIO.read(imageFile);
// clone the above BufferedImage object
BufferedImage bufferedImage2 = ImageUtils.clone(bufferedImage1);
// compare the above two objects
if (bufferedImage1 == bufferedImage2) {
System.out.println("The above two objects are the same.");
} else {
System.out.println("The above two objects are the different.");
}
}
}
The output result we should get is:
The above two objects are the different.