data2image/FileImageConverter.class.php

104 lines
2.1 KiB
PHP

<?php
/**
* This class will be able to convert a file into an image.
* @author JPT
*/
class FileImageConverter {
/**
* @var BoxImage
*/
protected $image;
/**
* @var CharColorConverter
*/
protected $colorConverter;
/**
* Default constructor
* @return void
*/
public function __construct() {
$this->colorConverter = new CharColorConverter();
}
/**
* Processes the given file, returns the filename of the resulting PNG-File.
* @param string $filename
* @return void
* @throws Exception
*/
public function convertFile($filename) {
if(file_exists($filename) === FALSE) throw new Exception("Invalid filename given!");
//get file data
$filesize = filesize($filename);
$md5 = md5_file($filename);
$new_filename = "result.png";
$header = "";
for($i = 0;$i < 255;$i += 5) {
$header .= chr($i);
}
$header .= chr(0);
$header .= $filesize;
$header .= chr(0);
$header .= $md5;
//header done, now read the file content
$content = file_get_contents($filename);
//get size for the image
$size = strlen($header) + 1 + $filesize;
//create and prepare image
$this->image = new BoxImage($size);
$this->image->fillImage(0,0,0,127);
//header first
$this->addDataToImage($header);
//magic pixel
$this->image->setCurrentPixel(0,0,0,127);
$this->image->movePointer(1);
//content
$this->addDataToImage($content);
//save image
$this->image->writeToFile($new_filename, 0);
//clean up
unset($this->image);
}
/**
* Converts data and adds it to the image.
* @param string $data
* @return void
*/
protected function addDataToImage($data) {
try {
$strlen = strlen($data);
for($i = 0;$i < $strlen; $i++) {
$char = substr($data, $i, 1);
//convert char to color
list($r, $g, $b) = $this->colorConverter->charToColor($char);
//set the pixel
$this->image->setCurrentPixel($r, $g, $b, 0);
//move the pointer
$this->image->movePointer(1);
}
} catch (Exception $e) {
//TODO: handle weird shit?
echo "Caught Exception:\n";
echo $e;
}
}
}
?>