How to clone Image?
10,005
Solution 1
You can draw to a buffered image, so make a blank bufferedImage, create a graphics context from it, and draw your original image to it.
BufferedImage copyOfImage =
new BufferedImage(widthOfImage, heightOfImage, BufferedImage.TYPE_INT_RGB);
Graphics g = copyOfImage.createGraphics();
g.drawImage(originalImage, 0, 0, null);
Solution 2
There is another way:
BufferedImage copyOfImage = image.getSubimage(0, 0, image.getWidth, image.getHeight);
Comments
-
Cenius almost 2 years
I have an Image. I need to make a exactly copy of it and save it to BufferedImage, but there is no Image.clone(). The thing should be inside a calculating loop and so it should be really fast, no pixel-by-pixel copying. What's the best in perfomance method to do this?
-
Andrew Thompson over 12 yearsThat would lose transparency. If in doubt, use
TYPE_INT_ARGB
. -
Cenius over 12 yearsHm... This looks faster for me.
-
DavidPostill about 9 yearsCould you please edit your answer to give an explanation of why this code answers the question? Code-only answers are discouraged, because they don't teach the solution.
-
Harald K about 9 yearsNo, this won't work, as
copyOfImage
andimage
will share backing buffers (it will be a shallow copy). Edits made to one, will be reflected in the other. -
Harald K about 9 yearsAlways remember to
dispose()
theGraphics
object after use!