#!/usr/bin/perl # UCW Gallery: Prepare cache # (c) 2004--2012 Martin Mares use strict; use warnings; use lib '/home/mj/web/gal2'; use UCW::Gallery qw(%CF); use Image::Magick; use IO::Handle; use File::Spec; use File::Path; STDOUT->autoflush(1); UCW::Gallery::LoadConfig; my $photo_dir = $CF{'PhotoDir'}; my $photo_meta = File::Spec->catfile($photo_dir, 'gallery.meta'); print "Reading meta-data from $photo_meta\n"; -f $photo_meta or die "Cannot load $photo_meta\n"; my $meta = UCW::Gallery::ReadMeta($photo_meta); my $cache_dir = $CF{'CacheDir'}; if (-d $cache_dir) { print "Deleting old cache directory: $cache_dir\n"; File::Path::remove_tree($cache_dir); } print "Creating cache directory: $cache_dir\n"; File::Path::mkpath($cache_dir) or die "Unable to create $cache_dir: $!\n"; for my $thumb_fmt (keys %{$CF{'ThumbFormats'}}) { my ($tw, $th) = ($thumb_fmt =~ m{^(\d+)x(\d+)$}) or die "Cannot parse thumbnail format $thumb_fmt\n"; print "Generating $thumb_fmt thumbnails\n"; my $thumb_meta = {}; $meta->{thumb}->{$thumb_fmt} = $thumb_meta; my $thumb_dir = File::Spec->catfile($cache_dir, $thumb_fmt); -d $thumb_dir or File::Path::mkpath($thumb_dir) or die "Unable to create $thumb_dir: $!\n"; for my $id (@{$meta->{sequence}}) { my $m = $meta->{photo}->{$id} or die; print "\t$id: "; my $p = new Image::Magick; my $photo = File::Spec->catfile($photo_dir, "$id.jpg"); my $e; $e = $p->Read($photo) and die "Error reading $photo: $e"; my $w = $m->{w}; my $h = $m->{h}; if ($w > $tw) { my $s = $tw / $w; $w = $w * $s; $h = $h * $s; } if ($h > $th) { my $s = $th / $h; $w = $w * $s; $h = $h * $s; } $w = int($w); $h = int($h); print "${w}x${h} "; $p->Resize(width=>$w, height=>$h); my $out = File::Spec->catfile($thumb_dir, "$id.jpg"); my $tmp = "$photo.new"; $e = $p->Write($tmp) and die "Unable to write $tmp: $e"; rename $tmp, $out or die "Unable to rename $tmp to $out: $!\n"; $thumb_meta->{$id} = { 'w' => $w, 'h' => $h, }; print "... OK\n"; } } my $cache_meta = File::Spec->catfile($cache_dir, 'cache.meta'); print "Writing meta-data to $cache_meta\n"; UCW::Gallery::WriteMeta($cache_meta, $meta);