[英]PHP resize and watermarking images on the fly or create multiple versions?
[英]Create and render multiple images on the fly in PHP
我正在研究以下代碼。 為什么我無法即時將生成的圖像渲染到頁面上?
<?php
for ($i = 0; $i <= 3; $i++) {
$im = imagecreatetruecolor(320, 80);
$text_color = imagecolorallocate($im, 255, 255, 255);
imagestring($im, 20, 20, 5, "Test App", $text_color);
$img = imagejpeg($im, 'Test.jpg');
echo '<div class="map"><img src="'.$img.'" class="img-responsive" alt="Cinque Terre"></div>';
imagedestroy($im);
}
?>
我現在在輸出中得到的是
而圖像的src
屬性為1
!
捕獲字節流,然后進行轉換。 您需要base64_encode
原始字節。 然后在image標簽中使用它:
基本思路:
for ($i = 0; $i <= 3; $i++) {
ob_start(); // begin capture
$im = imagecreatetruecolor(320, 80);
$text_color = imagecolorallocate($im, 255, 255, 255);
imagestring($im, 20, 20, 5, "Test App " . ($i + 1), $text_color);
$img = imagejpeg($im, null, 100);
$raw = ob_get_clean(); // get
echo '<div class="map"><img src="data:image/jpeg;base64,'.base64_encode($raw).'" class="img-responsive" alt="Cinque Terre"></div>';
}
<img>標記要求您提供文件名。 因此,您需要保存文件,然后引用保存的名稱,或者需要使用類似以下方法嵌入圖像數據:
imagejpeg()
根據此處的文檔返回一個布爾值: PHP imagejpeg-表示是否成功創建了圖像流。
在顯示頁面上,您可以執行以下操作:
<div class="map">
<img src="image.php" class="img-responsive" alt="Cinque Terre">
</div>
創建一個名為image.php
的文件並將其設置為源:
<?php
$im = imagecreatetruecolor(320, 80);
$text_color = imagecolorallocate($im, 255, 255, 255);
imagestring($im, 20, 20, 5, "Test App", $text_color);
header('Content-Type: image/jpeg');
$img = imagejpeg($im);
imagedestroy($im);
?>
這實際上image.php
視為圖像文件。 您必須在輸出上正確設置標頭,而您的代碼示例不會這樣做。 瀏覽器需要知道如何處理數據流。
也許最好有兩個單獨的PHP文件:一個動態創建圖像並將數據作為JPEG圖像返回(例如image.php),另一個則呈現HTML代碼。 然后,您的HTML將包含以下內容:
<img src="image.php?param1=value1&moreParams">
另一個選擇是繼續使用單個PHP文件,並將二進制JPEG圖像轉換為base64字符串。 這是因為“ src”屬性要么需要“正常” URL,要么需要base64編碼的圖像數據。 看到這里: https : //stackoverflow.com/a/21606233/4555850
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.