mason/{.perl-lib/TrivGal,dhandler}: Make an image object.
[tgal] / mason / .perl-lib / TrivGal.pm
index 9822a0b..838de97 100644 (file)
@@ -29,7 +29,6 @@ use autodie qw{:all};
 
 use Errno;
 use Exporter qw{import};
-use File::Path qw{make_path};
 use File::stat;
 use Image::Imlib2;
 use User::pwent;
@@ -183,35 +182,55 @@ sub clean_temp_files () {
 ###--------------------------------------------------------------------------
 ### Scaled images.
 
-export qw{scaled};
-sub scaled ($$) {
-  my ($scale, $path) = @_;
-
-  my $sz = $SIZE{$scale} or die "unknown scale `$scale'";
-  my $imgpath = "$IMGROOT/$path";
-  my $ist = stat $imgpath or die "no image `$path'";
-  my $thumb = "$CACHE/scaled.$scale/$path";
-  my $thumburl = "$CACHEURL/scaled.$scale/$path";
-  my $tst = stat $thumb;
-  if (defined $tst && $tst->mtime > $ist->mtime) { return $thumburl; }
-  my ($dir, $base, $ext) = split_path $thumb;
-  my $ty = $TYPE{lc $ext} or die "unknown type `$ext'";
-
-  my $img = Image::Imlib2->load($imgpath);
-  my ($wd, $ht) = ($img->width, $img->height);
-  my $max = $wd > $ht ? $wd : $ht;
-  if ($max <= $sz) { return "$IMGURL/$path"; }
-  my $sc = $sz/$max;
-  my $scaled = $img->create_scaled_image($sc*$wd, $sc*$ht);
-
-  $scaled->image_set_format($ty->imlibfmt);
-  $scaled->set_quality(90);
-  my $new = "$TMP/t${$}$ext";
-  make_path $TMP;
-  $scaled->save($new);
-  make_path $dir;
-  rename $new, $thumb;
-  return $thumburl;
+package TrivGal::Image {
+  use File::Path qw{make_path};
+  use File::stat;
+
+  sub new ($$) {
+    my ($cls, $path) = @_;
+    my $imgpath = "$IMGROOT/$path";
+    my $st = stat $imgpath or die "no image `$path'";
+    return bless {
+      path => $path,
+      mtime => $st->mtime,
+      img => undef
+    }, $cls;
+  }
+
+  sub scale ($$) {
+    my ($me, $scale) = @_;
+
+    my $path = $me->{path};
+    my $sz = $SIZE{$scale} or die "unknown scale `$scale'";
+    my $thumb = "$CACHE/scale.$sz/$path";
+    my $thumburl = "$CACHEURL/scale.$sz/$path";
+    my $st = stat $thumb;
+    if (defined $st && $st->mtime > $me->{mtime}) { return $thumburl; }
+
+    my ($dir, $base, $ext) = TrivGal::split_path $thumb;
+    my $ty = $TYPE{lc $ext} or die "unknown type `$ext'";
+
+    my $img = $me->{img};
+    unless (defined $img) {
+      my $imgpath = "$IMGROOT/$path";
+      $img = $me->{img} = Image::Imlib2->load($imgpath);
+    }
+
+    my ($wd, $ht) = ($img->width, $img->height);
+    my $max = $wd > $ht ? $wd : $ht;
+    if ($max <= $sz) { return "$IMGURL/$path"; }
+    my $sc = $sz/$max;
+    my $scaled = $img->create_scaled_image($sc*$wd, $sc*$ht);
+
+    $scaled->image_set_format($ty->imlibfmt);
+    $scaled->set_quality(90);
+    my $new = "$TMP/t${$}$ext";
+    make_path $TMP;
+    $scaled->save($new);
+    make_path $dir;
+    rename $new, $thumb;
+    return $thumburl;
+  }
 }
 
 ###--------------------------------------------------------------------------