php:BMP转PNG图像

2 篇文章 0 订阅

一、按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);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值