多次看到有人需要在网页里使用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;
}
...全文
111 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
faisun 2006-03-28
  • 打赏
  • 举报
回复
支持,帮顶

21,887

社区成员

发帖
与我相关
我的任务
社区描述
从PHP安装配置,PHP入门,PHP基础到PHP应用
社区管理员
  • 基础编程社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧