php - 如何在 PHP 中克隆 gd 资源

标签 php image gd

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

正如评论中所说,不,你不能做这样简单的感情:

$copy = $original;

这是因为资源是引用,不能像标量值一样被复制。

示例:

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

var_dump($a, $b);

// resource(2, gd)

// resource(2, gd)

最佳答案

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

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

关于php - 如何在 PHP 中克隆 gd 资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12605768/

相关文章:

image - 将弹出图像保持在窗口内并保持纵横比

html - Gmail 阻止电子邮件模板中的小型嵌入式内联图像

即使文件未丢失,Perl 可执行文件也会崩溃

php - 用GD创建一张包含其他图片的图片

php - 什么会导致 imagecolorsforindex() 出现 "color index out of range"错误?

php - 存储 html 模板的最佳方式 (Laravel 5)

php - CodeIgniter - 从 n-2-n 关系表中获取并显示数据

php - 周数格式 {YYYY}W{WW} 的 strftime 给出了错误的周

html - div 中的图像在图像下方有额外的空间

php - 使用 <select> 标签从数据库发布信息而无需提交按钮