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);
Share:
10,005
Cenius
Author by

Cenius

Programmer on C++ / Java / PHP and scripted languages.

Updated on June 19, 2022

Comments

  • Cenius
    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
    Andrew Thompson over 12 years
    That would lose transparency. If in doubt, use TYPE_INT_ARGB.
  • Cenius
    Cenius over 12 years
    Hm... This looks faster for me.
  • DavidPostill
    DavidPostill about 9 years
    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.
  • Harald K
    Harald K about 9 years
    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
    Harald K about 9 years
    Always remember to dispose() the Graphics object after use!