Greetings fellow monks,
Inspired by this, I decided to build a little script to build a collage image from book covers based on a source graphic. The script uses Amazon Web Services (or E-Commerse Service) to fetch book cover images based on an item search query. Then Image::Magick builds the collage.
To keep things simple, I saved all the images in grayscale. Mostly this was just a proof of concept to show how easy this sort of thing can be. Because I used AWS to get the cover art (and because I work at Amazon and can't resist the urge to suck-up), I used an image of Jeff Bezos I got here as the source image.
#!/usr/bin/perl
use strict;
use warnings;
use LWP;
use XML::XPath;
use Image::Magick;
my $size = 2; # 20 is "normal" but 2 is much smaller (better) resolu
+tion
my $ua = new LWP::UserAgent;
my $covers = new Image::Magick;
my $bezos = new Image::Magick;
my ($page, $t_pages, $image, %colors) = (1, 1, 0, undef);
while (($t_pages >= $page) and ($page < 26)) {
my $req = $ua->get(
'http://xml.amazon.com/onca/xml?Service=AWSECommerceService' .
'&Operation=ItemSearch&SubscriptionId=ADDYOURSUBSCRIPTIONIDHERE' .
'&SearchIndex=Books&Keywords=Amazon&ResponseGroup=Images' .
'&ItemPage=' . $page
);
die $! unless ($req->is_success);
my $xp = XML::XPath->new(xml => $req->content);
$t_pages = int($xp->findvalue('//Items/TotalPages')) if ($page == 1)
+;
my $nodeset = $xp->find('//Items/Item/SmallImage/URL');
foreach ($nodeset->get_nodelist) {
my $img = $ua->get($_->string_value);
die $! unless ($img->is_success);
open(IMG, '> covers/cover_' . $image . '.jpg') or die $!;
binmode IMG;
print IMG $img->content;
close IMG;
$covers->Read('covers/cover_' . $image . '.jpg');
my $scaled_img = $covers->[$image]->Clone();
$covers->[$image]->Scale(width => 40, height => 60);
$covers->[$image]->Quantize(colorspace=>'gray');
$covers->[$image]->Write('covers/cover_' . $image . '.jpg');
$scaled_img->Scale(width => 1, height => 1);
$colors{
eval(join('+', split(',', $scaled_img->Get('pixel[1,1]'))))
} = $image;
$image++;
}
$page++;
}
$bezos->Read('bezos.jpg');
my $width = $bezos->Get('columns');
my $height = $bezos->Get('rows');
my $width_i = $size * 2;
my $height_i = $size * 3;
my $w_stop = int($width / $width_i) * $width_i;
my $h_stop = int($height / $height_i) * $height_i;
print '<table border="0" cellspacing="0" cellpadding="0">', "\n";
for (my $y = 0; $y < $h_stop; $y += $height_i) {
print " <tr>\n";
for (my $x = 0; $x < $w_stop; $x += $width_i) {
my $bezos_section = $bezos->Clone();
$bezos_section->Crop(
geometry => $width_i . 'x' . $height_i . '+' . $x . '+' . $y
);
$bezos_section->Scale(width => 1, height => 1);
my $color = eval(join('+', split(',', $bezos_section->Get('pixel[1
+,1]'))));
my %compare = map { abs($color - $_) => $_ } keys %colors;
print ' <td><img src="covers/cover_',
$colors{$compare{(sort {$a<=>$b} keys %compare)[0]}},
'.jpg" width="', $width_i, '" height="', $height_i, '"/></td>', "
+\n";
}
print " </tr>\n";
}
print "</table>\n";