#!/usr/bin/perl # UCW Gallery: Generate published photos # (c) 2004--2012 Martin Mares use strict; use warnings; use UCW::Gallery; use Image::Magick; use IO::Handle; use File::Spec; use File::Path; STDOUT->autoflush(1); my $gal = UCW::Gallery->load_config; my $orig_list = $gal->read_list('gallery.list') or die "Cannot read gallery.list: $!\n"; my $photo_dir = $gal->get('PhotoDir'); if (-d $photo_dir) { print "Using existing output directory: $photo_dir\n"; } else { print "Creating output directory: $photo_dir\n"; File::Path::mkpath($photo_dir) or die "Unable to create $photo_dir: $!\n"; } my $photo_meta = $photo_dir . "/gallery.meta"; my $old_meta = {}; if (-f $photo_meta) { print "Reading old meta-data\n"; $old_meta = $gal->read_meta($photo_meta); # use Data::Dumper; print "Read old meta: ", Dumper($old_meta), "\n"; } my $meta = { 'photo' => {} }; for my $f (@$orig_list) { my $id = $f->{id}; my $rotate = $f->{orientation}; my $xfrm = $f->{xfrm}; print "$id: "; my $p = new Image::Magick; my $orig = File::Spec->rel2abs($f->{file}, $gal->get('OrigDir')); my ($orig_w, $orig_h, $orig_size, $orig_format) = $p->PingImage($orig) or die "Error reading $orig\n"; print "${orig_w}x${orig_h} "; my ($w0, $h0) = ($rotate eq "l" || $rotate eq "r") ? ($orig_h, $orig_w) : ($orig_w, $orig_h); my ($w, $h) = ($w0, $h0); if ($w > $gal->get('PhotoMaxWidth')) { my $s = $gal->get('PhotoMaxWidth') / $w; $w = $w * $s; $h = $h * $s; } if ($h > $gal->get('PhotoMaxHeight')) { my $s = $gal->get('PhotoMaxHeight') / $h; $w = $w * $s; $h = $h * $s; } $w = int($w); $h = int($h); my $m = { 'o' => $rotate, 'xf' => $xfrm, 'w' => $w, 'h' => $h, }; $meta->{photo}->{$id} = $m; my $om = $old_meta->{photo}->{$id}; if ($om && $om->{o} eq $m->{o} && $om->{xf} eq $m->{xf} && $om->{w} eq $m->{w} && $om->{h} eq $m->{h}) { # FIXME: Remove old images? print "... uptodate\n"; next; } my $e; $e = $p->Read($orig) and die "Error reading $orig: $e"; $p->Strip; $p->SetAttribute(quality=>90); if ($xfrm =~ /s/) { print "-> sharpen "; $p->Sharpen(1); } if ($xfrm =~ /h/) { print "-> equalize "; $p->Equalize(); } if ($xfrm =~ /n/) { print "-> normalize "; $p->Normalize(); } my $rot = 0; if ($rotate eq "l") { $rot = 270; } elsif ($rotate eq "r") { $rot = 90; } elsif ($rotate eq "u") { $rot = 180; } if ($rot) { print "-> rotate $rot "; $p->Rotate(degrees=>$rot); } if ($w != $w0 || $h != $h0) { print "-> ${w}x${h} "; $p->Resize(width=>$w, height=>$h); } my $photo = File::Spec->catfile($photo_dir, $id . ".jpg"); my $tmp = "$photo.new"; $e = $p->Write($tmp) and die "Unable to write $tmp: $e"; rename $tmp, $photo or die "Cannot rename $tmp to $photo: $!\n"; print "... OK\n"; } print "Cleaning up stale files\n"; for my $f (<$photo_dir/*.jpg>) { my ($vv, $dd, $id) = File::Spec->splitpath($f); $id =~ s{\..*$}{}; unless (defined $meta->{photo}->{$id}) { print "$id: removing\n"; unlink $f; } } print "Writing meta-data\n"; $gal->write_meta($photo_meta, $meta);