Finally completed, had a lot of problems with saving as an image file. But saving the image was a part of the other code i wrote, this code simply output's the image to the browser rather than saving it.
There is still one thing i didnt figure out, and thats how to dynamically generate a bmp header, so i stored a default 20x20 header.
The code itself has potential to input many more different colour codes, i just simply took the basic colours:
Black, Grey, White, Red, Green, Blue.
Click the link for a working example:
Create an image using php
Code: Select all
<?php
# create an image using php only
# no GD functions or command line.
#
# idea:
# take an array input,
# convert w : ff ff ff : white
# convert B : 00 00 00 : black
# convert G : 55 55 55 : grey
# convert r : ff 00 00 : red
# convert g : 00 ff 00 : green
# convert b : 00 00 ff : blue
$fromChr = array("w","B","G","r","g","b");
$toHex = array("ff ff ff","00 00 00","55 55 55", "ff 00 00", "00 ff 00", "00 00 ff");
# store the bmp header (20x20)
$header = "42 4d 00 00 00 00 00 00 00 00 36 00 00 00 28 00 00 00 14 00 00 00 14 00 00 00 01 00 18 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ";
# create the image string (20x20)
$imageArray = array(
"b b b b b b b b b b b b b b b b b b b b ",
"b B B B B B B B B B B B B B B B B B B b ",
"b B r r r r r r r r r r r r r r r r B b ",
"b B r g w w w w w w w w w w w w g r B b ",
"b B r g w G w w w w G w w w G w g r B b ",
"b B r g w G w w w w G w w w G w g r B b ",
"b B r g w G w w w w G w w w w w g r B b ",
"b B r g w G w w w w G w w w G w g r B b ",
"b B r g w G w w w w G w w w G w g r B b ",
"b B r g w G G G G G G w w w G w g r B b ",
"b B r g w G w w w w G w w w G w g r B b ",
"b B r g w G w w w w G w w w G w g r B b ",
"b B r g w G w w w w G w w w G w g r B b ",
"b B r g w G w w w w G w w w G w g r B b ",
"b B r g w G w w w w G w w w G w g r B b ",
"b B r g w G w w w w G w w w G w g r B b ",
"b B r g w w w w w w w w w w w w g r B b ",
"b B r r r r r r r r r r r r r r r r B b ",
"b B B B B B B B B B B B B B B B B B B b ",
"b b b b b b b b b b b b b b b b b b b b ");
#---------
# Reverse the string to match bmp storage format
$hexString = "";
foreach($imageArray as $string){
$hexString .= str_replace($fromChr,$toHex,implode(array_reverse(str_split($string))));
}
$imgArr = array_reverse(str_split($hexString));
#---------
# Add the BMP header for a (20x20) image.
$bmpHex = $header.implode($imgArr);
//header('Last-Modified: '.date('r'));
header('Content-Length: '.strlen($bmpHex));
header('Content-Type: image/bmp');
print pack('H*',implode(explode(" ",$bmpHex)));
?>
Edit:
Updated some depreciated variable names