dswsl2016
dswsl2016
2012-09-26 15:57
浏览 10
已采纳

如何在PHP中克隆gd资源

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)
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • doushaju4901
    doushaju4901 2012-09-26 16:53
    已采纳

    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;
    }
    
    点赞 评论
  • douyu7879
    douyu7879 2013-02-04 16:05

    This little function will clone an image resource while retaining 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;
    }
    
    点赞 评论
  • dongqu7778
    dongqu7778 2018-03-11 20:50

    Much simpler code, one line, handle transparency:

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

相关推荐