Skip to content
Advertisement

How to clone a gd resource in PHP

I’m looking for cloning an image in PHP created with imagecreatetruecolor or some other image creation function..

As it was said in the comment, no you can’t do a simple affection like :

$copy = $original;

This because ressources are reference and could not be copied like scalar values.

Example :

$a = imagecreatetruecolor(10,10);
$b = $a;

var_dump($a, $b);

// resource(2, gd)

// resource(2, gd)

Advertisement

Answer

So, the solution found was in the comment, and this is an implementation of it in a Image management class :

public function __clone() {
    $original = $this->_img;
    $copy = imagecreatetruecolor($this->_width, $this->_height);

    imagecopy($copy, $original, 0, 0, 0, 0, $this->_width, $this->_height);

    $this->_img = $copy;
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement