summaryrefslogtreecommitdiff
path: root/slice.raku
blob: 17c8aecd64ad43fbc8de08ef67814c303d7cbad1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/usr/bin/env raku

class Image {
  has Str $!source;
  has Str $!thumb;
  has Str $!blur;
  has Str $!large;

  submethod BUILD(IO::Path :$source, Str :$dist-dir) {
    $!source = $source.path;
    $!thumb = "$dist-dir/thumb/{$source.basename}";
    $!blur = "$dist-dir/blur/{$source.basename}";
    $!large = "$dist-dir/large/{$source.basename}";
  }

  method generate(Int :$thumb-geometry, Str :$bg-blur) {
    cmd 'convert', ['-auto-orient', '-geometry', $thumb-geometry,
                    $!source, $!thumb]
        unless $!thumb.IO.f;

    cmd 'convert', ['-flip', '-geometry', $thumb-geometry/2,
                    '-blur', $bg-blur,
                    $!source, $!blur]
        unless $!blur.IO.f;

    cmd 'cp', [$!source, $!large] unless $!large.IO.f;
  }
}

sub cmd(Str $command, @args) {
  say "=> {$command} {@args}";
  my $proc = run $command, @args, :out, :err;
  for $proc.out.slurp(:close), $proc.err.slurp(:close) {
    .say if .chars > 0;
  }
}

sub make-mr-proper(:$dist-dir) {
  cmd 'rm', <-r -f>, $dist-dir if $dist-dir.IO.d;
}

sub ensure-directories(:$dist-dir) {
  mkdir $dist-dir unless $dist-dir.IO.d;
  .IO.d or mkdir $_ for $dist-dir <<~>> </large /blur /thumb>;
}

multi MAIN(
  Bool :$mr-proper,           #= Clean output dir
  Str :$in-dir = './in',      #= Input dir
  Str :$dist-dir = './dist',  #= Output dir
  Int :$thumb-geometry = 800, #= Thumbnail geometry
  Str :$bg-blur = '0x8',      #= Background blur factor
) {

  my @images = dir($in-dir, test => { "$in-dir/$_".IO.f });

  make-mr-proper :$dist-dir if $mr-proper;
  ensure-directories :$dist-dir;

  @images.hyper.map({
    my $image = Image.new: source => $_, :$dist-dir;
    $image.generate: :$thumb-geometry, :$bg-blur;
  });
}