image conversion - PNG to Monochrome Bitmap for Thermal Printer in PHP?

545

I'm trying to dynamically generate QR codes for my thermal printer. In order to do this, I have to send a request to my server (say something like http://domain.example.com/qr?url=).

This page should then go and get a QR code from Google in PNG format. So far so good.

But now the difficult part. Once I have done that, I need to convert it to something along the lines of this.

I have previously found this question, but, unlike him, I need to do it on the web. I don't have access to installing PHP modules on the server, and so the best option for me, as far as I know, is phMagik, but again the problem is that as far as I know this does not support the extra parameters that can be fed into the normal Linux or Windows version of ImageMagik, as detailed on this documentation page.

So does anyone know how I could get round this problem? In the long term I'm hoping to make my own version of the Little Printer. Thanks.

994

Answer

Solution:

Just use the normal linux version of ImageMagick - call it usingexec()

If you don't have access to install things on your server, then it's going to get a little more complicated. If you have GD installed (you probably do), you can use http://php.net/imagecreatefrompng to get at the pixel data. You can then manually create the thing you're looking for, something like this:

$file = "/path/to/png.png"; 
$image = ImageCreateFromPng($file); 
list($w, $h) = GetImageSize($file); 

$pixels = array();
for ($x=0; $x<$w; $x++){
for ($y=0; $y<$h; $y++){
    $rgb = ImageColorAt($image, $x, $y); 
    $r = ($rgb >> 16) & 0xFF;
    $g = ($rgb >> 8) & 0xFF;
    $b = $rgb & 0xFF;
    $pixels = '0x'.sprintf('%02x', ($r+$g+$b)/3); # store the average of r/g/b
}
}

echo "static unsigned char __attribute__ ((progmem)) adalogo [] = {\n";
echo implode(', ', $pixels);
echo "};\n";

You need to first get the actual PNG - you could either fetch it via URL if you have file wrappers enabled:

$file = "http://url.com/to/png.png"; 
$image = ImageCreateFromPng($file); 

Or use PHP on the command line first the grab the image:

$file = "/path/to/png.png"; 
exec("php /path/to/script.php > $file");
$image = ImageCreateFromPng($file); 

People are also looking for solutions to the problem: PHP - trying to send email from script with attachment, but its not attachingHi

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.