Caching Remote Images · Nov 26, 01:45 PM by Dylan Doxey
So, you want to display someone else's images on your website, but you don't want to be guilty of "hot linking"?
Here's a handy way to cache remote images in Perl.
#!/usr/bin/perl
use strict;
use LWP::Simple;
my $remote_location = 'http://dylan.doxey.org/gallery/galleries/Computer_stuff/';
my $local_location = './';
my @image_names = (
'09-24-06_180836.jpg',
'09-24-06_111144.jpg',
'09-22-06_005014.jpg',
);
foreach my $image_name (@image_names) {
my $remote_image_name = $remote_location . $image_name;
my $local_image_name = cache_remote_image( $remote_image_name, $local_location );
print "Remote file: " . $remote_image_name
. "\n"
. " Saved as: " . $local_image_name
. "\n";
}
sub cache_remote_image {
my ( $remote_image_name, $local_location ) = @_;
my @remote_name_components = split( '/', $remote_image_name );
my $local_image_name = $local_location . $remote_name_components[-1];
my $image_data = get( $remote_image_name );
open my $local_image_fh, '>', $local_image_name or die "Open for write failed: $!";
binmode( $local_image_fh );
print $local_image_fh $image_data;
close( $local_image_fh );
return $local_image_name;
}
1;

Commenting is closed for this article.
