我的php文件創建一個png圖像。圖像已準備好並保存到給定文件夾中,但無法將其加載到頁面上(它只顯示圖像的位置,但是爲空)。PHP文件作爲圖像源不起作用(HTML,PHP)
這是 「captcha_image.php」:
<?php
$dirPath="/opt/lampp/htdocs/WebSiteFolder/dfxCaptcha/";
$font='/opt/lampp/htdocs/WebSiteFolder/DejaVuSerif-Bold.ttf';
$imgWidth=200;
$imgHeight=50;
global $image;
$image = imagecreatetruecolor($imgWidth, $imgHeight) or die("Cannot initialize a new GD image stream.");
$background_color = imagecolorallocate($image, 0, 0, 0);
$text_color = imagecolorallocate($image, 255, 255, 255);
imagefilledrectangle($image, 0, 0, $imgWidth, $imgHeight, $background_color);
$letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$len = strlen($letters);
$letter = $letters[rand(0, $len - 1)];
$word = "";
for ($i = 0; $i < 4; $i++) {
$letter = $letters[rand(0, $len - 1)];
imagettftext($image, 15, 0, $i*50+25, 50, $text_color, $font, $letter);
$word .= $letter;
}
$_SESSION['captcha_string'] = $word;
$images = glob($dirPath."*.png");
foreach ($images as $image_to_delete) {
@unlink($image_to_delete);
}
header ("Content-type: image/png");
imagepng($image, $dirPath."image" . time() . ".png");
?>
我在HTML中使用這樣的:
<img src="includes/captcha_image.php" id="captcha">
我如何可以顯示圖像的網頁?
那麼,我是否需要先運行php文件,並使用png文件作爲源代碼加載創建的圖像之後? – ZsG
@ZsG不,如果您對'img'標記使用'src =「includes/captcha_image.php」',則PHP文件將執行,創建一個圖像,然後直接將其提供給瀏覽器,而無需將其另存爲一個PNG文件。您只需確保PHP文件實際呈現爲PNG文件,我的答案應該解決這個問題。 –
@ZsG此外,如果你沒有存儲你的圖像,你不需要'$ dirPath'變量或腳本中的整個文件刪除邏輯。 –