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?
How to clone Image?
Take a look at this #3514658 –
Swede
It copies Image pixel-by-pixel (just copies the raster data). Is there any way to do it faster? –
Masaryk
If you want a deep copy, there is no other way I know about. And why do you want to clone it every loop iteration? –
Swede
Actually I need to make a lot of image copies which is rotated by 1 degree, so I need to copy basic image and perform some operations on it. –
Masaryk
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);
That would lose transparency. If in doubt, use
TYPE_INT_ARGB
. –
Irksome Hm... This looks faster for me. –
Masaryk
Always remember to
dispose()
the Graphics
object after use! –
Rogation There is another way:
BufferedImage copyOfImage = image.getSubimage(0, 0, image.getWidth, image.getHeight);
No, this won't work, as
copyOfImage
and image
will share backing buffers (it will be a shallow copy). Edits made to one, will be reflected in the other. –
Rogation Image clone = original.getScaledInstance(original.getWidth(), -1, Image.SCALE_DEFAULT);
This might not be very pretty, but getScaledInstance
returns, as the name suggests, an instance of your original Image
object. Usually only used for resizing. -1
tells the method to keep the aspect ratio as it is
Could 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. –
Radioluminescence
You can create a method that returns the subimage of the image you want to clone.
Such as:
public static BufferedImage clone(BufferedImage img)
{
return img.getSubimage(img.getMinX(), img.getMinY(), img.getWidth(), img.getHeight());
}
© 2022 - 2025 — McMap. All rights reserved.