word/edit: precalculate image width and height
[sheet.git] / Shiar_Sheet / ImagePrep.pm
1 package Shiar_Sheet::ImagePrep;
2
3 use 5.014;
4 use warnings;
5
6 our $VERSION = '1.00';
7
8 sub new {
9         my ($class, $target) = @_;
10         bless \$target, $class;
11 }
12
13 sub download {
14         # copy changed remote url to local file
15         my $target = shift;
16         unlink $$target if -e $$target;
17         my $download = shift or return 1;
18         require LWP::UserAgent;
19         my $ua = LWP::UserAgent->new;
20         $ua->agent('/');
21         my $status = $ua->mirror($download, $$target);
22         $status->is_success
23                 or die "Download from <q>$download</q> failed: ".$status->status_line."\n";
24 }
25
26 sub convert {
27         my ($imgpath, $thumbpath, $cmds) = @_;
28         if (not -e $$imgpath) {
29                 return !-e $thumbpath || unlink $thumbpath;
30         }
31
32         my $xyres = 0 ? '600x400' : '300x200'; # cover
33         my @cmds = @{ $cmds // [] };
34         if (my ($cmdarg) = grep { $cmds[$_] eq '-area' } 0 .. $#cmds) {
35                 # replace option by permillage crop
36                 my @dim = map { $_ / 1000 } split /\D/, $cmds[$cmdarg + 1];
37                 $dim[$_] ||= 1 for 2, 3; # optional end
38                 push @dim, $dim[2 + $_] - $dim[$_] for 0, 1; # add width, height
39                 splice @cmds, $cmdarg, 2, (
40                         -set => 'option:distort:viewport' => sprintf(
41                                 '%%[fx:%s]x%%[fx:%s]+%%[fx:%s]+%%[fx:%s]',
42                                 "w*$dim[4]", "h*$dim[5]", # width x height
43                                 "w*$dim[0]", "h*$dim[1]", # x+y offset
44                         ),
45                         -distort => SRT => 0, # noop transform to apply viewport
46                 );
47         }
48         @cmds = (
49                 'convert',
50                 $$imgpath,
51                 -delete => '1--1', -background => 'white',
52                 -gravity => defined $cmds ? 'northwest' : 'center',
53                 @cmds,
54                 -resize => "$xyres^", -extent => $xyres,
55                 '-strip', -quality => '60%', -interlace => 'plane',
56                 $thumbpath
57         );
58
59         require IPC::Run;
60         my $output;
61         IPC::Run::run(\@cmds, '<' => \undef, '>&' => \$output) or die [
62                 "Failed to convert source image.",
63                 "@cmds\n" .
64                 ($output || ($? & 127 ? "signal $?" : "error code ".($? >> 8))),
65         ];
66 }
67
68 1;