确保imagepng已经在服务器上写入了文件



我有一个在现有qr码图像下添加文本的函数。在某些情况下,返回的速度比服务器在文件系统上写入映像的速度要快,因此其他函数会出现问题。

如何确保在返回图像路径之前完成所有操作?目前我正在尝试使用while-loop,但我也非常不满意它。这也会导致服务器超时和崩溃(不知道为什么)。

function addTextToQrCode($oldImage, $text)
{
$newImage = $oldImage;
$newImage = str_replace(".png", "_original.png", $newImage);
copy($oldImage, $newImage);
$image = imagecreatefrompng($oldImage);
$black = imagecolorallocate($image, 0, 0, 0);
$fontSize = 20;
$textWidth = imagefontwidth($fontSize) * strlen($text);
$textHeight = imagefontheight($fontSize);
$x = imagesx($image) / 2  - $textWidth / 2;
$y = imagesy($image) - $textHeight - 3;
imagestring($image, 5, $x, $y, $text, $black);
$filePath = "/qrCodes/qrcode".$text.'.png';
imagepng($image, $filePath);

while(!$this->checkIfNewQrCodeIsOnFileSystem($filePath)){
$this->checkIfNewQrCodeIsOnFileSystem($filePath);
}
return $filePath;

}
function checkIfNewQrCodeIsOnFileSystem($filePath) {
if (file_exists($filePath)) {
return true;
} else {
return false;
}
}

只检查imagepng()。这是我更喜欢的解决方案。

function addTextToQrCode($oldImage, $text)
{
$newImage = $oldImage;
$newImage = str_replace(".png", "_original.png", $newImage);
copy($oldImage, $newImage);
$image = imagecreatefrompng($oldImage);
$black = imagecolorallocate($image, 0, 0, 0);
$fontSize = 20;
$textWidth = imagefontwidth($fontSize) * strlen($text);
$textHeight = imagefontheight($fontSize);
$x = imagesx($image) / 2  - $textWidth / 2;
$y = imagesy($image) - $textHeight - 3;
imagestring($image, 5, $x, $y, $text, $black);
$filePath = "/qrCodes/qrcode".$text.'.png';
if (imagepng($image, $filePath) === true) {
return $filePath;
} 

}

最新更新