我正在寻找用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)
这个小函数将克隆图像资源,同时保留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)
所以,找到的解决方案是在评论中,这是它在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)
| 归档时间: |
|
| 查看次数: |
5476 次 |
| 最近记录: |