I have the following php script:
<?php
class GimFile {
public $data = '';
public $header = '';
public $rgba = '';
public $width = 0;
public $height = 0;
public function __construct($imagedata) {
$this->data = $imagedata;
if (substr($this->data, 1, 3) != 'GIM') {
exit("This data is not in GIM format");
}
$this->header = substr($this->data, 0, 128);
$this->rgba = substr($this->data, 128);
// PHP can't unpack signed short from big-endian
// so we unpack it as unsigned, and subtract 2^16 if >2^15
$dimensions = array_values(unpack("n2", substr($this->header, 72, 76)));
for($i = 0; $i < count($dimensions); $i++) {
if($dimensions[$i] >= pow(2, 15)) {
$dimensions[$i] -= pow(2, 16);
}
}
list($this->width, $this->height) = $dimensions;
}
public function save($dest) {
//create image
$img = imagecreatetruecolor($this->width, $this->height);
//fill by iterating through your raw pixel data
for($x = 0; $x < $this->width; $x++) {
for($y = 0; $y < $this->height; $y++) {
$pos = ($y * $this->width + $x) * 4;
list($red, $green, $blue, $alpha) = array_values(unpack("C4", substr($this->rgba, $pos, $pos+4)));
$alpha >>= 1; // alpha transprancy is saved as 8bit, we need 7 bit
$color = imagecolorallocatealpha ( $img, $red, $green, $blue, $alpha );
imagesetpixel($img, $x, $y, $color);
}
}
imagepng($img, $dest);
imagedestroy($img);
}
}
header('Content-type: image/png');
$contents = file_get_contents('gim');
$gim = new GimFile($contents);
$gim->save('lol.png');
?>
It is supposed to read get raw binary data as an argument, and save this as a .png file. This data, contains the following:
first 128 byte are the headers, of which offset 72 and 74 contain width and height respectively (signed short big endian). This data is parsed in the constructor. The rest of the data is raw RGBA data.
The save function, goes through the raw RGBA data (iterating through every pixel), finds the colour, and writes to a new image of same width and height. and then saves it to a file.
however, the results are wrong for some reason.
The following file is used that contains the data needed: http://2971.a.hostable.me/gim/gim
The following png is expected: http://2971.a.hostable.me/gim/expected.png
The following png is generated: http://2971.a.hostable.me/gim/output.png
To closest i came to the expected result, was by setting the $alpha to 0, but that resulted in this: http://2971.a.hostable.me/gim/noalpha.png
Can anyone help to fix the script to produce the expected result?
Thanks in advance.
Hosh