| 1 | package Deployer::Image::PNG; | ||
| 2 | BEGIN { | ||
| 3 | $Deployer::Image::PNG::VERSION = '0.06'; | ||
| 4 | } | ||
| 5 | |||
| 6 | # ABSTRACT: Thing wrapper around PNG image for size optimization | ||
| 7 | |||
| 8 | use Moose; | ||
| 9 | |||
| 10 | use Path::Class; | ||
| 11 | |||
| 12 | |||
| 13 | has 'filename' => ( | ||
| 14 | is => 'rw', | ||
| 15 | |||
| 16 | required => 1 | ||
| 17 | ); | ||
| 18 | |||
| 19 | |||
| 20 | has 'iterations' => ( | ||
| 21 | is => 'rw', | ||
| 22 | |||
| 23 | default => sub { 1 } | ||
| 24 | ); | ||
| 25 | |||
| 26 | |||
| 27 | has 'use_lossless' => ( | ||
| 28 | is => 'rw', | ||
| 29 | |||
| 30 | default => sub { 1 } | ||
| 31 | ); | ||
| 32 | |||
| 33 | |||
| 34 | has 'use_optipng' => ( | ||
| 35 | is => 'rw', | ||
| 36 | |||
| 37 | default => sub { 1 } | ||
| 38 | ); | ||
| 39 | |||
| 40 | |||
| 41 | has 'use_pngout' => ( | ||
| 42 | is => 'rw', | ||
| 43 | |||
| 44 | default => sub { 1 } | ||
| 45 | ); | ||
| 46 | |||
| 47 | |||
| 48 | has 'use_quantization' => ( | ||
| 49 | is => 'rw', | ||
| 50 | |||
| 51 | default => sub { 1 } | ||
| 52 | ); | ||
| 53 | |||
| 54 | |||
| 55 | has 'png_out_binary' => ( | ||
| 56 | is => 'rw' | ||
| 57 | ); | ||
| 58 | |||
| 59 | |||
| 60 | sub get_size { | ||
| 61 | my ($self) = @_; | ||
| 62 | |||
| 63 | return file($self->filename)->stat->size; | ||
| 64 | } | ||
| 65 | |||
| 66 | |||
| 67 | |||
| 68 | sub optimize { | ||
| 69 | my ($self) = @_; | ||
| 70 | |||
| 71 | for (my $i = 0; $i < $self->iterations; $i++) { | ||
| 72 | |||
| 73 | $self->quantize() if $self->use_quantization; | ||
| 74 | $self->optimize_lossless() if $self->use_lossless; | ||
| 75 | } | ||
| 76 | |||
| 77 | } | ||
| 78 | |||
| 79 | |||
| 80 | sub optimize_lossless { | ||
| 81 | my ($self) = @_; | ||
| 82 | |||
| 83 | my $file = $self->filename; | ||
| 84 | my $pngout = $self->png_out_binary; | ||
| 85 | |||
| 86 | qx!optipng -q -o3 $file! if $self->use_optipng; | ||
| 87 | qx!$pngout -q -y $file! if $self->use_pngout; | ||
| 88 | } | ||
| 89 | |||
| 90 | |||
| 91 | sub quantize { | ||
| 92 | my ($self) = @_; | ||
| 93 | |||
| 94 | my $file = $self->filename; | ||
| 95 | |||
| 96 | my $file_nq8 = $file; | ||
| 97 | $file_nq8 =~ s/\.png$/-nq8.png/; | ||
| 98 | |||
| 99 | |||
| 100 | my $before = file($file)->stat->size; | ||
| 101 | |||
| 102 | qx!pngnq -s 1 -Q f $file 2> /dev/null!; | ||
| 103 | |||
| 104 | my $after = file($file_nq8)->stat->size; | ||
| 105 | |||
| 106 | |||
| 107 | if ($after < $before) { | ||
| 108 | `mv -f $file_nq8 $file`; | ||
| 109 | } else { | ||
| 110 | unlink($file_nq8); | ||
| 111 | } | ||
| 112 | } | ||
| 113 | |||
| 114 | __PACKAGE__ | ||
| 115 | __END__ |