How to clone a gd resource in PHP

I'm looking for image cloning in PHP created using imagecreatetruecolor or some other image creation function.

As the comment said, no, you cannot do simple attachment like:

 $copy = $original; 

This is because ressources are referenced and cannot be copied as scalar values.

Example:

 $a = imagecreatetruecolor(10,10); $b = $a; var_dump($a, $b); // resource(2, gd) // resource(2, gd) 
+7
source share
3 answers

So, the solution found was in a comment, and this is its implementation in the 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; } 
+6
source

This small feature will clone the image resource while preserving the alpha channel (transparency).

 function _clone_img_resource($img) { //Get width from image. $w = imagesx($img); //Get height from image. $h = imagesy($img); //Get the transparent color from a 256 palette image. $trans = imagecolortransparent($img); //If this is a true color image... if (imageistruecolor($img)) { $clone = imagecreatetruecolor($w, $h); imagealphablending($clone, false); imagesavealpha($clone, true); } //If this is a 256 color palette image... else { $clone = imagecreate($w, $h); //If the image has transparency... if($trans >= 0) { $rgb = imagecolorsforindex($img, $trans); imagesavealpha($clone, true); $trans_index = imagecolorallocatealpha($clone, $rgb['red'], $rgb['green'], $rgb['blue'], $rgb['alpha']); imagefill($clone, 0, 0, $trans_index); } } //Create the Clone!! imagecopy($clone, $img, 0, 0, 0, 0, $w, $h); return $clone; } 
+6
source

Simpler code, one line, descriptor transparency:

 function clone_img_resource($img) { return imagecrop($img, array('x'=>0,'y'=>0,'width'=>imagesx($img),'height'=>imagesy($img))); } 
0
source

All Articles