May 5, 2009

ActionScript: Printing

function print_mc(mc) {
 
 var myPrintJob:PrintJob = new PrintJob();

 myPrintJob.start();
 myPrintJob.addPage(mc);
 myPrintJob.send();

}

PHP: generate a photographic mosaic

I have written a command-line, procedural PHP script to generate a photographic mosaic.

Some samples:




The script works in two stages. The first one scans all of the images to work out an average color, and saves that information to a txt file on the disk.

This is then used in the second stage of the process, where a template of the mosaic is made - this is an image, shrinked down in size to as many pixels as is the number of images on the horizontal and vertical axis. This way each image represents one pixel of the template. The second stage begins composing the mosaic from images, that have the closest average color to the current pixel in the template.

The process is optimized by caching average colors to disk (this optimization is mandatory) and an caching smaller images to disk (there's a BIG difference in speed if you try to open a 5MB file or 100K file).

Here's the code that does all the work: http://pastebin.com/f70e3ccf7

May 1, 2009

PHP: average functions: Mean (Arithmetic, Geometric, Harmonic) · Median · Mode

See Wiki for detail on mean, median or mode. Please write your own optimizations / implementations in the comments.
function arithmetic_mean($a) {
 return array_sum($a)/count($a);
}

function geometric_mean($a) {
 foreach($a as $i=>$n) $mul = $i == 0 ? $n : $mul*$n;
 return pow($mul,1/count($a));
}

function harmonic_mean($a) {
 $sum = 0;
 foreach($a as $n) $sum += 1 / $n;
 return (1/$sum)*count($a);
}

function median($a) {
 sort($a,SORT_NUMERIC); 
 return (count($a) % 2) ? 
  $a[floor(count($a)/2)] : 
  ($a[floor(count($a)/2)] + $a[floor(count($a)/2) - 1]) / 2;
}

function modal_score($a) {
 $quant = array();
 foreach($a as $n) $quant["$n"]++;
 $max = 0;
 $mode = 0;
 foreach($quant as $key=>$n) {
  if($n>$max) {
   $max = $n;
   $mode = $key;
  }
 }
 return $mode;
}