如何在PHP中克隆gd资源

Let*_*eto 7 php gd image

我正在寻找用PHP imagecreatetruecolor或其他图像创建功能创建的PHP克隆图像.

正如在评论中所说,不,你不能做一个简单的感情,如:

$copy = $original;
Run Code Online (Sandbox Code Playgroud)

这是因为ressources是引用,无法像标量值那样被复制.

示例:

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

var_dump($a, $b);

// resource(2, gd)

// resource(2, gd)
Run Code Online (Sandbox Code Playgroud)

Dru*_*ver 7

这个小函数将克隆图像资源,同时保留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;
}
Run Code Online (Sandbox Code Playgroud)


Let*_*eto 6

所以,找到的解决方案是在评论中,这是它在Image管理类中的实现:

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 这实际上不会克隆图像资源,只是将位图画布复制到另一个新的资源对象并忽略来自原始资源的所有其他设置,例如 alpha 透明度、混合、某些颜色设置等。当您尝试使用透明 PNG 时(或 GIF)图层,您更有可能获得黑色背景而不是透明色。对于非透明图像,这仍然有效。 (2认同)