Saturday, November 20, 2010

Get flag images from Wikipedia

I needed a large number of national flag images at a certain resolution for a project my Web Development course was working on. By examining some flag images I saw on Wikipedia, I noticed that they were creating flag images on the fly.

For example, to create the United Kingdom's flag that is 100 pixels wide, you can access this URL:

http://upload.wikimedia.org/wikipedia/commons/thumb/4/45/Flag_of_the_United_Kingdom.svg/100px-the_United_Kingdom.png

which produces this flag:

So I developed a Perl script that would automate this process for me. I've included it below for anyone else who might need flag images. Note that I had to set the user agent string, or Wikipedia would not respond properly to the http request. If you use this script to download a lot of images, please be nice throttle your requests with the sleep() command.

01#!/usr/bin/perl
02 
03# This script will attempt to download the national flag
04# produced by Wikipedia using the $flag country name and
05# $image_size as the image width.  By Frank McCown.
06 
07use LWP::Simple;
08use HTTP::Response;
09use strict;
10 
11# Width of the image
12my $image_size = 100;
13 
14# Country's name
15my $flag = 'the United Kingdom';
16 
17my $filename = lc $flag;
18$filename =~ s/\s/_/g;
19$filename = $filename . "_" . $image_size . ".png";
20 
21my $url_filename = $flag;
22$url_filename =~ s/\s/_/g;
23 
25$url_filename . ".svg/" . $image_size . "px-" . $url_filename . ".png";
26 
27print "Getting $img_url\n";
28 
29my $ua = LWP::UserAgent->new;
30$ua->agent('Mozilla/5.0 Firefox 5.6');
31$ua->from('your@email.com');
32 
33my $response = $ua->get($img_url);
34 
35if ($response->is_success) {
36   print "Writing to $filename\n";
37 
38   open(IMG, ">$filename");
39   binmode(IMG);
40   print IMG $response->content;
41   close IMG;
42}
43else {
44   print "ERROR: Could not download.\n";
45}

No comments:

Post a Comment