我正在寻找用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;
}