我正在寻找 flock() 图像。
目前我正在使用以下
$img = ImageCreateFromPng($img_path);
flock($img,LOCK_EX);
似乎GD库的文件句柄对flock无效。如何访问图像并聚集文件?
该函数flock
仅适用于文件句柄(或支持锁定的流包装器)。因此,如果您想在阅读时锁定图像,则需要将其打开两次:
$f = fopen($imgPath, 'r');
if (!$f) {
//Handle error (file does not exist perhaps, or no permissions?)
}
if (flock($f, LOCK_EX)) {
$img = imagecreatefrompng($imgPath);
//... Do your stuff here
flock($f, LOCK_UN);
}
fclose($f);
您的示例中的 $img 不是文件句柄,它是内存中 GD 图像资源的句柄。
您可以使用 imagecreatefromstring 来加载这样的图像:
$file=fopen($fileName,"r+b");
flock($file,LOCK_EX);
$imageBinary=stream_get_contents($file);
$img=imagecreatefromstring($imageBinary);
unset($imageBinary); // we don't need this anymore - it saves a lot of memory
如果要将图像的修改版本保存到打开的流中,则必须使用输出缓冲:
ob_start();
imagepng($img);
$imageBinary=ob_get_clean();
ftruncate($file,0);
fseek($file,0);
fwrite($file,$imageBinary);
unset($imageBinary);
flock($file,LOCK_UN);
fclose($file);
flock
仅适用于文件指针并且ImageCreateFromPng
仅适用于文件名。尝试拨打两个不同的电话:
$fp = fopen($img_path, 'r');
flock($fp, LOCK_EX);
$img = ImageCreateFromPng($img_path);
flock
是合作的,所以它只有在每个人都使用它的情况下才有效。只要ImageCreateFromPng
不使用flock
,上面的代码应该可以工作。