2013-11-04 47 views
0

我在瀏覽器中回顯圖像時遇到了一些困難。我對PHP很陌生,在過去的一個小時裏我一直在網上搜索,但沒有找到解決方案。我曾嘗試將header('Content-Type: image/jpeg'); 添加到文檔中,但它什麼都不做。我希望我的代碼能夠掃描目錄,並將其所有圖像文件放入$ thumbArray中,然後我將回顯給瀏覽器。我的最終目標是照相館。將圖像插入數組可以正常工作,但不會在頁面上顯示它們。這裏是我的我的代碼:難以迴應JPEG圖像

<?php 

//Directory that contains the photos 
$dir = 'PhotoDir/'; 

//Check to make sure the directory path is valid 
if(is_dir($dir)) 
{ 
    //Scandir returns an array of all the files in the directory 
    $files = scandir($dir); 
} 



//Declare array 
$thumbArray = Array(); 

foreach($files as $file) 
{ 
    if ($file != "." && $file != "..")  //Check that the files are images 
     array_push($thumbArray, $file); //array_push will add the $file to thumbarray at index count - 1 
} 


print_r($thumbArray); 


include 'gallery.html'; 

?> 

繼承人的Gallery.html文件:

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
    <title>Gallery</title> 
</head> 
<body> 


    <?php 
    header('Content-Type: image/jpeg'); 

    for($i = 0; $i < count($thumbArray); $i++) 
    echo '<img src="$dir'.$thumbArray[$i].'" alt="Picture" />'; 

    ?> 

</body> 
</html> 
+1

'''' – Petah

+0

用你的替換我的線不能解決我的問題。我仍然可以看到帶有摺頁角的小方框,而不是我的圖像。 – Whoppa

回答

4

對於您目前的情況,只是從你的代碼中刪除header('Content-Type: image/jpeg');。您的輸出是HTML。所有圖像都在IMG標籤內輸出。在這種情況下不需要額外的頭部修改。

此外,如果您要使用PHP,請不要將此代碼放在* .html文件中。它不會在默認http-server設置下的* .html中運行。將gallery.html重命名爲gallery.php並將include 'gallery.html';更改爲include 'gallery.php';,它會正常工作(當然,如果您也刪除了header('Content-Type: image/jpeg');)。

三壞事:

echo '<img src="$dir'.$thumbArray[$i].'" alt="Picture" />'; 

你試圖把$dir可變進單引號。只有雙引號允許你在裏面使用PHP變量。

更改:

echo '<img src="'.$dir.$thumbArray[$i].'" alt="Picture" />'; 

改變後,請,請查看網頁的源代碼,並檢查您的圖片路徑是正確的。如果不是,請採取措施糾正它。例如,您可能忘記了目錄分隔符和正確的字符串:

echo '<img src="'.$dir.'/'.$thumbArray[$i].'" alt="Picture" />'; 

依此類推。

+0

謝謝!它現在工作完美!只是好奇,什麼時候需要指定標題類型? – Whoppa

+1

@Whoppa,如果您的輸出是原始JPEG(二進制JPEG文件內容),PDF,PNG或任何不是HTML的文件,則需要設置其他標頭。否則不。 –

+0

哦,我明白了。謝謝。 – Whoppa