2016-09-01 27 views
0

您可以看看這段代碼,並讓我知道爲什麼我無法將生成的圖像呈現在頁面上嗎?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); 
    } 
?> 

我在輸出我得到現在是

enter image description here

,而圖像的src屬性1

enter image description here

+2

'$ img'被設置爲true,因爲'imagejpeg()'返回一個布爾值。 – Blake

回答

2

捕獲字節流,然後轉換。你需要base64_encode原始字節。然後在圖像標籤使用它:

基本思想:

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>'; 
} 
+1

該答案對於該問題是完整的,並且應該爲詢問問題的人員工作。 –

0

的<IMG>標籤期望你提供一個文件名。因此,你需要保存文件,然後引用保存的名稱或您需要在使用這樣的嵌入圖像數據:

Embedding Base64 Images

+0

您不需要保存任何圖像文件來引用它。 – Blake

0

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爲圖像文件。您必須在輸出上正確設置標題,這是您的代碼示例不會執行的。瀏覽器需要知道如何處理數據流。

+0

這顯然只是一個圖像的一個例子,但您可以隨身攜帶並運行它。 – Blake

0

也許最好是有兩個獨立的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