Converting images between formats
I wanted to convert a bitmap (.bmp) image to an ascii art here the other day.
I did ls /usr/bin/*toascii and found a program to convert from pbm to ascii (pbmtoascii) from the netpbm package. That was swell. So I did another ls /usr/bin/*topbm to find a way of doing a .pbm image. I got a list of programs but alas no bmptopbm.
So after contemplating usage of the many online ascii art generators I decided to do the least cost effective thing and write a program to determine possible conversion paths from one format to another using the netpbm and other packages out there.
I tried writing a recursive function that looked for converters until all of them would be found, but due to the nature of the netpbm-package some image-formats are only convertible to one other format and some are convertible to multiple formats. That meant that I have a lot pitfalls in terms of writing a good recursive function to find all of them. Multiple loops to get stuck in. So I gave the job to my CPU and decided to not spend my time scratching my head for a recursive routine. In stead I would map out all the converters in a couple of layers in both directions and use Dijkstra or some other graph-traversing algorithm to find the way to go.
#!/usr/bin/perl
use Graph;
my $g = Graph->new;
$input = $ARGV[0];
$output = $ARGV[1];
$g->add_vertex($input);
$g->add_vertex($output);
my @toOutput = &findTo($output);
foreach my $format ( @toOutput) {
$g->add_vertex($format);
$g->add_path($format,$output);
my @levelTwo = &findTo($format);
foreach my $forma (@levelTwo) {
$g->add_vertex($forma);
$g->add_path($forma,$format);
and so on and so forth. And thus be able to do:
print “Graph: $g \n”;
@path = $g->SP_Dijkstra($input,$output); if (!@path) { print “No path\n”; }
else { print “Dijkstra-Path: @path \n”; }
And that would yield, when running for instance find bmp ascii:
Dijkstra-Path: bmp ppm pgm pbm ascii
And thus I found a way of converting a .bmp to a .ppm and convert the .ppm to a .pgm to be converted to a .pbm and lastly from .pbm to .ascii. Adding a couple of lines to map the graph point that is the mighty ImageMagick convert tool I can then convert from jpeg to ascii doing the extra step from jpeg to bmp.
So if anybody wonders … for instance how to convert a .st4-file to .tiff here’s the solution:
st4 to pgm, pgm to pbm, pbm to gem, gem to pnm, pnm to tiff…
Or maybe you are wondering how to convert a PostScript file to ascii in a completely useless way? :
ps to pnm, pnm to jpeg, jpeg to bmp, bmp to ppm, ppm to pgm, pgm to pbm, pbm to ascii