#!/usr/bin/perl use strict; use warnings; use CGI qw(:standard); use File::Type; use File::stat; use Image::Magick; my $DIR = "."; #where to look for the files my $percent = 10; #size of the thumbnails my $author = 'gabri.mate@modernbiztonsag.org'; #page author #convert and create thumbnail sub create_thumbnail { my $file = $_[0]; my $image = Image::Magick->new(); $image->Read("$file"); if ( $_[1] ) { #convert section my $oldfile = $file; my @file = split(/\./,$file); $file = $file[0] . ".jpg"; open(IMAGE, ">$file") || die "Can't open $file!"; $image->Write(file=>\*IMAGE, filename=>$file); close(IMAGE); $image = Image::Magick->new(); $image->Read("$file"); unlink($oldfile) || die "Can't unlink $oldfile!"; } my ($width, $height) = $image->Get('width', 'height'); $width = $width * $percent / 100; $height = $height * $percent / 100; $image->Scale(width=>"$width", height=>"$height"); $image->Write("thumbs/$file"); } #check if source file is updated since last thumbnail creation sub check_mtime { my $file = $_[0]; if ( ! -d "$DIR/thumbs/$file") { return(1); } my $filetime = stat($file)->mtime; my $thumbtime = stat("$DIR/thumbs/$file")->mtime; if ( $filetime > $thumbtime ) { return(1); } else { return(0); } } #check is file is an image and if it has a thumbnail or not sub check_mime_type { my $file = $_[0]; my $ft = File::Type->new(); my $type = $ft->mime_type($file); if ( $type =~ /image/ and $type !~ /jpeg/ ) { &create_thumbnail($file,1); } #if image is not jpeg then convert before creating thumbnail elsif ( $type =~ /image\/jpeg/ and &check_mtime($file) ) { &create_thumbnail($file); } #if image is jpeg and hasn't got a thumbnail, or thumbnail is out of date compared to the source image, then create one } #look for files in $DIR sub collect_files { if ( ! -d "$DIR/thumbs" ) { mkdir("$DIR/thumbs") || die "Can't create $DIR/thumbs"; } #create thumbs subdir to pleace thumbnails there serving as cache opendir(DIR, "$DIR") || die "Can't open $DIR!"; while (defined(my $file = readdir(DIR))) { if ( ! -d $file ) { &check_mime_type($file); } } closedir(DIR); } #collect files, create thumbnails and pass list of images back to cgi output sub collect_thumbs { &collect_files; my @thumbs; opendir(DIR, "$DIR/thumbs") || die "Can't open $DIR/thumbs!"; while (defined(my $file = readdir(DIR))) { if ( ! -d "$DIR/thumbs/$file" ) { push(@thumbs, $file); } } closedir(DIR); return @thumbs; } #cgi output sub index { print header; print start_html( -title=>'Thumbnail index', -author=>"$author", ); my @thumbs = &collect_thumbs; foreach (@thumbs) { print "\n"; } print end_html(); } &index;