chiark / gitweb /
mason/.perl-lib/TrivGal.pm (Image::scale): Check size much earlier.
[tgal] / mason / .perl-lib / TrivGal.pm
index e97ffb687f78c1ab3937cede7eda98dfbca6fe7a..513a68262f813b8f3cce4875feea124a48cb5a21 100644 (file)
@@ -32,6 +32,7 @@ use Exporter qw{import};
 use File::stat;
 use Image::ExifTool qw{};
 use Image::Imlib2;
+use Image::Size qw{};
 use User::pwent;
 use POSIX;
 
@@ -213,18 +214,35 @@ package TrivGal::Image {
     my $imgpath = "$IMGROOT/$path";
     my $st = stat $imgpath or die "no image `$path'";
     return bless {
-      path => $path,
+      path => $path, imgpath => $imgpath,
       mtime => $st->mtime,
-      img => undef
+      img => undef,
+      _wd => undef, _ht => undef,
+      sz => undef
     }, $cls;
   }
 
+  sub _getsz ($) {
+    my ($me) = @_;
+    return if defined $me->{_wd};
+
+    my ($wd, $ht, $err) = Image::Size::imgsize $me->{imgpath};
+    defined $wd or die "failed to read size of `$me->{path}': $err";
+    my $sz = $wd; if ($sz < $ht) { $sz = $ht; }
+    @$me{"_wd", "_ht", "sz"} = ($wd, $ht, $sz);
+  }
+
+  sub sz ($) { my ($me) = @_; $me->_getsz; return $me->{sz}; }
+
   sub scale ($$;$) {
     my ($me, $scale, $forcep) = @_;
     my $m = HTML::Mason::Request->instance;
 
     my $path = $me->{path};
     my $sz = $SIZE{$scale} or die "unknown scale `$scale'";
+    if ($me->sz <= $sz)
+      { return $m->interp->apply_escapes("$IMGURL/$path", "u"); }
+
     my $thumb = "$CACHE/scale.$sz/$path";
     my $thumburl =
       $m->interp->apply_escapes("$CACHEURL/scale.$sz/$path", "u");
@@ -239,11 +257,10 @@ package TrivGal::Image {
 
     my $img = $me->{img};
     unless (defined $img) {
-      my $imgpath = "$IMGROOT/$path";
       my $exif = new Image::ExifTool;
-      $exif->ExtractInfo($imgpath);
+      $exif->ExtractInfo($me->{imgpath});
       my $orient = $exif->GetValue("Orientation", "ValueConv");
-      $img = $me->{img} = Image::Imlib2->load($imgpath);
+      $img = $me->{img} = Image::Imlib2->load($me->{imgpath});
       if (defined $orient) {
        my ($rot, $flip) = @{$ORIENT{$orient}};
        if ($rot) { $img->image_orientate($rot); }
@@ -251,10 +268,7 @@ package TrivGal::Image {
       }
     }
 
-    my ($wd, $ht) = ($img->width, $img->height);
-    my $max = $wd > $ht ? $wd : $ht;
-    if ($max <= $sz) { return "$IMGURL/$path"; }
-    my $sc = $sz/$max;
+    my $sc = $sz/$me->sz;
     my $scaled = $img->create_scaled_image($sc*$wd, $sc*$ht);
 
     $scaled->image_set_format($ty->imlibfmt);