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?

Cenius
  • 103
  • 1
  • 1
  • 9
  • 1
    Take a look at this http://stackoverflow.com/questions/3514158/how-do-you-clone-a-bufferedimage – user219882 Jan 14 '12 at 18:17
  • 1
    It copies Image pixel-by-pixel (just copies the raster data). Is there any way to do it faster? – Cenius Jan 14 '12 at 18:19
  • 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? – user219882 Jan 14 '12 at 22:30
  • 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. – Cenius Jan 16 '12 at 20:23

4 Answers4

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);
frictionlesspulley
  • 11,070
  • 14
  • 66
  • 115
Levster
  • 146
  • 1
1

There is another way:

BufferedImage copyOfImage = image.getSubimage(0, 0, image.getWidth, image.getHeight);
Angelo Alvisi
  • 480
  • 1
  • 4
  • 15
  • 3
    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. – Harald K Mar 19 '15 at 11:57
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

phil294
  • 10,038
  • 8
  • 65
  • 98
  • 1
    Could you please [edit] your answer to give an explanation of why this code answers the question? Code-only answers are [discouraged](http://meta.stackexchange.com/questions/148272), because they don't teach the solution. – DavidPostill Mar 19 '15 at 06:57
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());
}
Adan Vivero
  • 422
  • 12
  • 36