2011-06-07 45 views
17

php如何獲得kb中的web圖像大小?php如何獲得kb中的web圖像大小?

getimagesize只得到寬度和高度。

filesize引起的waring

$imgsize=filesize("http://static.adzerk.net/Advertisers/2564.jpg"); 
echo $imgsize; 

Warning: filesize() [function.filesize]: stat failed for http://static.adzerk.net/Advertisers/2564.jpg

是否有任何其他的方式來獲得以KB爲Web圖像的大小?

+1

[PHP:遠程文件的大小,而無需下載文件]中可能重複(http://stackoverflow.com/questions/2602612/php-remote-file-size-without-downloading-file) – deceze 2011-06-07 23:25:29

+0

這似乎是相關的:[link] http://stackoverflow.com/questions/2145021/php-getimagesize-alternatives-without-javascript [/ link] – knurdy 2011-06-07 23:27:40

回答

18

短做一個完整的HTTP請求,有沒有簡單的方法:

$img = get_headers("http://static.adzerk.net/Advertisers/2564.jpg", 1); 
print $img["Content-Length"]; 

然而,您可能會利用cURL發送lighter HEAD request instead

+0

很好,get_headers運行得更快。謝謝。 – 2011-06-07 23:32:18

+2

確保你的HTTP客戶端沒有發送任何頭文件,說它接受gzip的HTTP響應,否則'Content-Length'將會出錯,因爲服務器會發送壓縮的數據。 – Darien 2011-06-07 23:39:14

+0

@Darien:非常棒!幸運的是'get_headers'發送一個非常簡單的HTTP/1.0請求。但對於捲曲,這需要更多的努力。 – mario 2011-06-07 23:48:38

3

這聽起來像一個權限問題,因爲filesize()應該工作得很好。

下面是一個例子:

php > echo filesize("./9832712.jpg"); 
1433719 

確保權限設置正確的圖像並且路徑也是正確的。你將需要應用一些數學轉換從字節到KB,但做完後你應該保持良好狀態!

5
<?php 
$file_size = filesize($_SERVER['DOCUMENT_ROOT']."/Advertisers/2564.jpg"); // Get file size in bytes 
$file_size = $file_size/1024; // Get file size in KB 
echo $file_size; // Echo file size 
?> 
1

這裏是一個很好的關於鏈接文件大小()

不能使用文件大小()來檢索遠程文件信息。它首先必須通過另一種方法

使用此捲曲被下載或確定是一個很好的方法:

Tutorial

1

您也可以使用此功能

<?php 
$filesize=file_get_size($dir.'/'.$ff); 
$filesize=$filesize/1024;// to convert in KB 
echo $filesize; 


function file_get_size($file) { 
    //open file 
    $fh = fopen($file, "r"); 
    //declare some variables 
    $size = "0"; 
    $char = ""; 
    //set file pointer to 0; I'm a little bit paranoid, you can remove this 
    fseek($fh, 0, SEEK_SET); 
    //set multiplicator to zero 
    $count = 0; 
    while (true) { 
     //jump 1 MB forward in file 
     fseek($fh, 1048576, SEEK_CUR); 
     //check if we actually left the file 
     if (($char = fgetc($fh)) !== false) { 
      //if not, go on 
      $count ++; 
     } else { 
      //else jump back where we were before leaving and exit loop 
      fseek($fh, -1048576, SEEK_CUR); 
      break; 
     } 
    } 
    //we could make $count jumps, so the file is at least $count * 1.000001 MB large 
    //1048577 because we jump 1 MB and fgetc goes 1 B forward too 
    $size = bcmul("1048577", $count); 
    //now count the last few bytes; they're always less than 1048576 so it's quite fast 
    $fine = 0; 
    while(false !== ($char = fgetc($fh))) { 
     $fine ++; 
    } 
    //and add them 
    $size = bcadd($size, $fine); 
    fclose($fh); 
    return $size; 
} 
?> 
0

您可以通過使用get_headers()函數來獲取文件的大小。使用下面的代碼:

$image = get_headers($url, 1); 
    $bytes = $image["Content-Length"]; 
    $mb = $bytes/(1024 * 1024); 
    echo number_format($mb,2) . " MB"; 
相關問題