如何克隆在PHP GD资源(How to clone a gd resource in PHP)

2019-09-23 01:49发布

我正在寻找在PHP克隆图像与创建imagecreatetruecolor或其他一些图像创建功能..

由于这是在评论说,不,你不能做一个简单的感情,如:

$copy = $original;

这是因为ressources是参考,不能被复制像标量值。

例如:

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

var_dump($a, $b);

// resource(2, gd)

// resource(2, gd)

Answer 1:

同时保留了alpha通道(透明度)这个小函数将克隆的图像资源。

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;
}


Answer 2:

因此,找到了解决办法是在评论,这是它在图片管理类的实现:

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;
}


Answer 3:

更简单的代码,一条线,处理透明度:

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


文章来源: How to clone a gd resource in PHP
标签: php image gd