java创建bmp单色位图,在PHP中创建1位位图(单色)

I'm looking for the possibility of write a 1 bit bitmap from a string with this content:

$str = "001011000111110000";

Zero is white and One is black.

The BMP file will be 18 x 1 px.

I don't want a 24bit BMP, but a real 1bit BMP.

Does anyone know the header and the conversion method in PHP?

解决方案

That's a little bit of a strange request :)

So, what you'd want to use here is php-gd, for a start. Generally this is included when installing php on any OS with decent repo's, but just incase it isn't for you, you can get the installation instructions here;

First, we'll need to figure out exactly how big the image will need to be in width; height will obviously always be one.

So;

$str = $_GET['str'];

$img_width = strlen($str);

strlen will tell us how many characters are in the $str string, and since we're giving one pixel per character, the amount of characters will give us the required width.

For ease of access, split the string into an array - with each element for each separate pixel.

$color_array = str_split($str);

Now, let's set up a "pointer", for which pixel we're drawing to. It's php so you don't NEED to initalise this, but it's nice to be tidy.

$current_px = (int) 0;

And now you can initialise GD and start making the image;

$im = imagecreatetruecolor($img_width, 1);

// Initialise colours;

$black = imagecolorallocate($im, 0, 0, 0);

$white = imagecolorallocate($im, 255, 255, 255);

// Now, start running through the array

foreach ($color_array as $y)

{

if ($y == 1)

{

imagesetpixel ( $im, $current_px , 1 , $black );

}

$current_px++; // Don't need to "draw" a white pixel for 0. Just draw nothing and add to the counter.

}

This will draw your image, then all you need do is display it;

header('Content-type: image/png');

imagepng($im);

imagedestroy($im);

Note that the $white declaration isn't needed at all - I just left it in to give you an idea of how you declare different colours with gd.

You'll probably need to debug this a bit before using it - it's been a long time since I've used GD. Anyway, hope this helps!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值