一、按BMP(8bit)的调色板段和数据段格式可以容易获得BMP每个像素的RGB值,如下:
function address($name,$offset,$len=4) {
$ch = file_get_contents($name,'',null,$offset,$len);
$str = array();
for ($i = 0;$i < $len;$i++) {
$str[] = sprintf('%02X',ord($ch[$i]));
}
$str = array_reverse($str);
$str = implode('',$str);
return hexdec($str);
}
public function icolor($name,$top,$left)
{
$w=address($name,18);
$h=address($name,22);
$offset=$w*($h-$top-1)+$left;
$data=file_get_contents($name,'',null,54+1024,$w*$h);//获取数据段数据
$buffer=file_get_contents($name,'',null,54,1024);//获取调色板段数据
$ind=substr($data,$offset,1);
$ind=ord($ind);
$col=array();
for($i=0;$i<3;$i++)
{
$col[]= sprintf('%02X',ord(substr($buffer,$ind*4+$i,1)));
}
$col = array_reverse($col);
return implode('',$col);
}
$name='a.bmp';
icolor($name,0,0);//获取(0,0)像素的RGB
二、利用GD函数生成PNG图像
$name='a.bmp';
$w=address($name,18);
$h=address($name,22);
$im=imagecreatetruecolor($w,$h);
for($i=0;$i<$h;$i++)
{
for($j=0;$j<$w;$j++)
{
$rgb=icolor($name,$i,$j);
$r=hexdec(substr($rgb,0,2));
$g=hexdec(substr($rgb,2,2));
$b=hexdec(substr($rgb,4,2));
$co=imagecolorallocate($im, $r, $g, $b);
imagesetpixel($im,$j,$i,$co);
}
}
header("Content-Type: image/png");
imagepng($im);//输出到屏幕
imagedestroy($im);