多次看到有人需要在网页里使用bmp的,就写了一个bmp读取函数。方便大家把bmp存成jpg吧。
Gdj 2006-03-28 09:03:30 function imagecreatefrombmp($fname)
{
$buf=@file_get_contents($fname);
if(strlen($buf)<54) return false;
$file_header=unpack("sbfType/LbfSize/sbfReserved1/sbfReserved2/LbfOffBits",substr($buf,0,14));
if($file_header["bfType"]!=19778) return false;
$info_header=unpack("LbiSize/lbiWidth/lbiHeight/sbiPlanes/sbiBitCountLbiCompression/LbiSizeImage/lbiXPelsPerMeter/lbiYPelsPerMeter/LbiClrUsed/LbiClrImportant",substr($buf,14,40));
//懒得支持2色位图
if($info_header["biBitCountLbiCompression"]==2) return false;
$line_len=round($info_header["biWidth"]*$info_header["biBitCountLbiCompression"]/8);
$x=$line_len%4;
if($x>0) $line_len+=4-$x;
$img=imagecreatetruecolor($info_header["biWidth"],$info_header["biHeight"]);
switch($info_header["biBitCountLbiCompression"]){
case 4:
$colorset=unpack("L*",substr($buf,54,64));
for($y=0;$y<$info_header["biHeight"];$y++){
$colors=array();
$y_pos=$y*$line_len+$file_header["bfOffBits"];
for($x=0;$x<$info_header["biWidth"];$x++){
if($x%2)
$colors[]=$colorset[(ord($buf[$y_pos+($x+1)/2])&0xf)+1];
else
$colors[]=$colorset[((ord($buf[$y_pos+$x/2+1])>>4)&0xf)+1];
}
imagesetstyle($img,$colors);
imageline($img,0,$info_header["biHeight"]-$y-1,$info_header["biWidth"],$info_header["biHeight"]-$y-1,IMG_COLOR_STYLED);
}
break;
case 8:
$colorset=unpack("L*",substr($buf,54,1024));
for($y=0;$y<$info_header["biHeight"];$y++){
$colors=array();
$y_pos=$y*$line_len+$file_header["bfOffBits"];
for($x=0;$x<$info_header["biWidth"];$x++){
$colors[]=$colorset[ord($buf[$y_pos+$x])+1];
}
imagesetstyle($img,$colors);
imageline($img,0,$info_header["biHeight"]-$y-1,$info_header["biWidth"],$info_header["biHeight"]-$y-1,IMG_COLOR_STYLED);
}
break;
case 16:
for($y=0;$y<$info_header["biHeight"];$y++){
$colors=array();
$y_pos=$y*$line_len+$file_header["bfOffBits"];
for($x=0;$x<$info_header["biWidth"];$x++){
$i=$x*2;
$color=ord($buf[$y_pos+$i])|(ord($buf[$y_pos+$i+1])<<8);
$colors[]=imagecolorallocate($img,(($color>>10)&0x1f)*0xff/0x1f,(($color>>5)&0x1f)*0xff/0x1f,($color&0x1f)*0xff/0x1f);
}
imagesetstyle($img,$colors);
imageline($img,0,$info_header["biHeight"]-$y-1,$info_header["biWidth"],$info_header["biHeight"]-$y-1,IMG_COLOR_STYLED);
}
break;
case 24:
for($y=0;$y<$info_header["biHeight"];$y++){
$colors=array();
$y_pos=$y*$line_len+$file_header["bfOffBits"];
for($x=0;$x<$info_header["biWidth"];$x++){
$i=$x*3;
$colors[]=imagecolorallocate($img,ord($buf[$y_pos+$i+2]),ord($buf[$y_pos+$i+1]),ord($buf[$y_pos+$i]));
}
imagesetstyle($img,$colors);
imageline($img,0,$info_header["biHeight"]-$y-1,$info_header["biWidth"],$info_header["biHeight"]-$y-1,IMG_COLOR_STYLED);
}
break;
default:
return false;
break;
}
return $img;
}