#!/usr/bin/perl # UCW Gallery: Prepare cache # (c) 2004--2012 Martin Mares use strict; use warnings; use FindBin; use lib $FindBin::Bin; use UCW::Gallery; use Image::Magick; use IO::Handle; use File::Spec; use File::Path; STDOUT->autoflush(1); my $gal = UCW::Gallery->load_config; print "Reading gallery.list\n"; my $orig_list = $gal->read_list('gallery.list') or die "Cannot read gallery.list: $!\n"; my $photo_dir = $gal->get('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 = $gal->read_meta($photo_meta); my $cache_dir = $gal->get('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"; # Construct sequence and store photo titles $meta->{sequence} = []; for my $f (@$orig_list) { push @{$meta->{sequence}}, $f->{id}; my $m = $meta->{photo}->{$f->{id}} or die; $m->{title} = $f->{title}; } for my $thumb_fmt (keys %{$gal->get('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"; $gal->write_meta($cache_meta, $meta);