tags:

views:

17

answers:

1

This is a contrived example, but it illustrates my problem much more concisely then the code I'm using - and I've tested this and it exhibits the problem:

$image = imagecreatefromjpeg('test.jpg');    
$copy_of_image = $image;

// The important bit
imagedestroy($image);

header('Content-type: image/jpeg');
imagejpeg($copy_of_image);

Now, my expectation is that $copy_of_image is exactly that, but when I run this, it fails, printing out the URL of the script of all things. Comment out the imagedestroy() and it works just fine.

a var_dump of $image provides:

resource(3) of type (gd) 

So why can't I copy this? Apparently the assignment $copy_of_image = $image is creating a reference rather then a copy - is there a way to prevent that?

+1  A: 

The resource itself is a reference to an image. So, whether you copy or reference-assign it to another variable, the resource still references the same image. You're just making two references that both point to the same image. If you destroy the image (that's what imagedestroy does), the image is no longer available and any resource pointing to it becomes invalid.

You would need to create a new image with imagecreatetruecolor and copy the contents of the first image to the second using imagecopy. Or create two separate images with two separate resources using imagecreatefromjpeg in the first place.

deceze