Skip to content

Instantly share code, notes, and snippets.

@jmhobbs
Created March 15, 2010 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmhobbs/332950 to your computer and use it in GitHub Desktop.
Save jmhobbs/332950 to your computer and use it in GitHub Desktop.
Bitwise Data Vizualization in PHP
<?php
// Data Vizualization in PHP
// This file will render a 1024x1024 PNG using the raw binary data from a file.
// 1's will be black, 0's will be white.
/*
Copyright (c) 2010 John Hobbs
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
$width = 1024;
$height = 1024;
$filename = 'data.bin';
$pixels = $width * $height;
$image = imagecreate( $height, $width );
$white = imagecolorallocate( $image, 255, 255, 255 );
$black = imagecolorallocate( $image, 0, 0, 0 );
imagefill( $image, 0, 0, $white );
$fh = fopen( $filename, 'rb' );
if( ! $fh )
die( 'Could not open file handle.' );
$x = 0;
$y = 0;
$abort = false;
while( ! $abort && ! feof( $fh ) ) {
$byte = fread( $fh, 1 );
// PHP makes us juggle the binary data a bit...
$numbers = @unpack( "c", $byte );
$byte = $numbers[1];
for( $i = 7; $i >= 0; --$i ) {
$bit = ( ( $byte >> $i ) & 1 );
if( $bit == 1 )
imagesetpixel( $image, $x, $y, $black );
++$x;
if( $x >= $width ) {
++$y;
$x = 0;
}
if( $y >= $height ) {
$abort = true;
break;
}
}
}
fclose( $fh );
header( 'Content-type: image/png' );
imagepng ( $image );
imagedestroy( $image );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment