How to clone Image?
Asked Answered
M

4

8

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?

Masaryk answered 14/1, 2012 at 18:15 Comment(4)
Take a look at this #3514658Swede
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
M
9

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);
Mythopoeia answered 14/1, 2012 at 20:43 Comment(3)
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
E
1

There is another way:

BufferedImage copyOfImage = image.getSubimage(0, 0, image.getWidth, image.getHeight);
Eligibility answered 8/1, 2015 at 6:56 Comment(1)
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
K
0

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

Keelboat answered 18/3, 2015 at 21:3 Comment(1)
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
B
0

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());
}
Bernat answered 12/11, 2019 at 17:14 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.