# [J2ME] Image problem

## Recommended Posts

hi, i'd like to know how to make a copy of an Image? If i do this:
// Assume "orig" to be the original, existing image loaded from a PNG (128px x 128px)

Image a = Image.createImage(128, 128);

a = orig;

this is wrong right? a would be the same as orig, and when i set a to null, orig will also be null... please help. thanks.

anyone? thanks.

##### Share on other sites
Sneftel    1788
No, that's not the way objects work in Java. You're creating an image and making the variable "a" point to it. Then, on the next line, you make it so "a" no longer points to that image, and instead points to the same image that "orig" points to.

If you want to copy the contents of an image, use dest.getGraphics().drawImage(src, ....). However, I really suggest you spend some time learning Java before you continue with J2ME.... it will be very helpful in addressing these sorts of issues.

##### Share on other sites
Skizz    794
No, that won't create a copy of the image, only a copy of the reference to the image so drawing on one will affect the other. To create a new image you must do:
Image new_image = Image.createImage (old_image);

Skizz

##### Share on other sites
Skizz    794
...unless, of course, you want to modify the copy of the original image, in which case use Sneftel's method. My method always creates an immuatable copy/reference of the original if it was mutable/immutable.

Skizz

##### Share on other sites
whoops, i've solved this problem already...here's how i did it:

public void drawMe(Graphics p_G) {        Graphics _backup = p_G;        Image _nmdMiscBuffer = Image.createImage(128, 128);        p_G = _nmdMiscBuffer.getGraphics();        // Draw stuffs here...        p_G.setClip(...);        p_G.drawImage(...);        // End Draw stuffs        p_G = _backup;        p_G.setClip(0, 0, 128, 128);        p_G.drawImage(_nmdMiscBuffer, 0, 0, p_G.TOP|p_G.LEFT);        _nmdMiscBuffer = null;        _backup = null;}

Thanks anyway though. :)

##### Share on other sites
Sneftel    1788
Looks like you're trying to implement manual double-buffering. What phone are you targeting? Many have built-in double-buffering.

##### Share on other sites
nope...not really doing manual double-buffering...the game's a tiled game, and my idea of speeding the game up is to use whatever that can be reused in the previous frame rather than draw each tiles again...it really sped up the game big time though...:)

##### Share on other sites
CalvinCoder    139
Quote:
 Original post by _nomad_this is wrong right? a would be the same as orig, and when i set a to null, orig will also be null...

Yes, "a" would be the same as "orig" but no, setting "a" to null would not set "orig" to null. Setting "a" to null just deletes "a" as a reference to the image but orig will still keep the same reference to the image.