2010-10-29 43 views
6

我使用imagecreatefromjpeg,imagecreatefromgifimagecreatefrompng函數來創建縮略圖image/jpeg,image/gifimage/png啞劇。如何創建.BMP文件的縮略圖?

我也想創建.BMP文件的縮略圖。

我查了一個文件,發現它的mime是image/x-ms-bmp

但是,我找不到合適的imagecreatefrom...函數。

請建議。

+0

是的,看看這個PHP的手冊頁 - 提供了很多解決方案:http://us.php.net/manual/en/function.imagecreatefromwbmp.php – leepowers 2010-10-29 04:11:16

+0

非常感謝! – 2010-10-29 05:04:57

回答

11

PHP沒有內置在BMP圖像的功能。

已經有幾次嘗試創建函數來做到這一點。

你可以找到在PHP文檔中此評論一個強大的和有據可查的版本:http://www.php.net/manual/en/function.imagecreatefromwbmp.php#86214

這裏是沒有優秀的文檔該註釋的功能,這使得更長的時間,但更可讀:

public function imagecreatefrombmp($p_sFile) 
{ 
    $file = fopen($p_sFile,"rb"); 
    $read = fread($file,10); 
    while(!feof($file)&&($read<>"")) 
     $read .= fread($file,1024); 
    $temp = unpack("H*",$read); 
    $hex = $temp[1]; 
    $header = substr($hex,0,108); 
    if (substr($header,0,4)=="424d") 
    { 
     $header_parts = str_split($header,2); 
     $width   = hexdec($header_parts[19].$header_parts[18]); 
     $height   = hexdec($header_parts[23].$header_parts[22]); 
     unset($header_parts); 
    } 
    $x    = 0; 
    $y    = 1; 
    $image   = imagecreatetruecolor($width,$height); 
    $body   = substr($hex,108); 
    $body_size  = (strlen($body)/2); 
    $header_size = ($width*$height); 
    $usePadding  = ($body_size>($header_size*3)+4); 
    for ($i=0;$i<$body_size;$i+=3) 
    { 
     if ($x>=$width) 
     { 
      if ($usePadding) 
       $i += $width%4; 
      $x = 0; 
      $y++; 
      if ($y>$height) 
       break; 
     } 
     $i_pos = $i*2; 
     $r  = hexdec($body[$i_pos+4].$body[$i_pos+5]); 
     $g  = hexdec($body[$i_pos+2].$body[$i_pos+3]); 
     $b  = hexdec($body[$i_pos].$body[$i_pos+1]); 
     $color = imagecolorallocate($image,$r,$g,$b); 
     imagesetpixel($image,$x,$height-$y,$color); 
     $x++; 
    } 
    unset($body); 
    return $image; 
} 
+0

太棒了!非常感謝!! – 2010-10-29 05:04:03

+2

不適用於x-ms-bmp,'注意:未初始化的字符串偏移量會使圖像失真 – Sem 2013-03-13 11:02:52