├── LICENSE ├── README.md ├── jpegdropscan.md ├── jpegdropscan.pl ├── jpegultrascan.md └── jpegultrascan.pl /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JPEG recompressors 2 | [jpegultrascan](jpegultrascan.md) - JPEG lossless recompressor that tries all scan possibilities to minimize size 3 | 4 | [jpegdropscan](jpegdropscan.md) - JPEG lossy recompressor that removes least informative scans to reach a target quality 5 | -------------------------------------------------------------------------------- /jpegdropscan.md: -------------------------------------------------------------------------------- 1 | # jpegdropscan 2 | JPEG lossy recompressor that removes least informative scans to reach a target quality 3 | 4 | ## Command line usage 5 | perl jpegdropscan.pl [switches] inputfile outputfile 6 | 7 | ## Switches 8 | -d N Maximum quality metric difference level (default: 0) 9 | -r path Path to reference image to use with quality metric evaluator (default: inputfile) 10 | -n [N] Use quality (N = best, 100 default) rather than distance (0 = best) 11 | -q Suppress all output 12 | -v Verbose output 13 | -p path Path to jpegtran (default: jpegtran) 14 | -c path Path to quality metric evaluator (default: butteraugli) 15 | -b 0-13 Maximum number of bit splits to test (default: 3) 16 | 17 | ## Requirements 18 | - [Perl](https://www.perl.org/) 19 | - jpegtran from [libjpeg](https://jpegclub.org/reference/reference-sources/), [libjpeg-turbo](https://github.com/libjpeg-turbo/libjpeg-turbo), or [mozjpeg](https://github.com/mozilla/mozjpeg) 20 | - [butteraugli, SSIMULACRA 2](https://github.com/libjxl/libjxl) or other quality metric evaluator 21 | 22 | ## Notes 23 | Rather than recoding an image, jpegdropscan iteratively removes scan information starting with least significant bits and moving to least significant coefficients. Originally developed using butteraugli for quality evaluation, but other metrics may be used. 24 | 25 | Best results can be achieved by processing an image with [jpegultrascan](jpegultrascan.md) first, running jpegdropscan, then jpegultrascan once more. 26 | 27 | ## Author 28 | Aaron Kaluszka <> 29 | -------------------------------------------------------------------------------- /jpegdropscan.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | =head1 NAME 3 | jpegdropscan 4 | =head1 DESCRIPTION 5 | JPEG lossy recompressor that removes least informative scans to reach a target quality 6 | =head1 VERSION 7 | 1.1.1 2024-04-24 8 | =head1 LICENSE 9 | Copyright 2015 - 2024 Aaron Kaluszka 10 | 11 | Licensed under the Apache License, Version 2.0 (the "License"); 12 | you may not use this file except in compliance with the License. 13 | You may obtain a copy of the License at 14 | 15 | http://www.apache.org/licenses/LICENSE-2.0 16 | 17 | Unless required by applicable law or agreed to in writing, software 18 | distributed under the License is distributed on an "AS IS" BASIS, 19 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 20 | See the License for the specific language governing permissions and 21 | limitations under the License. 22 | =cut 23 | 24 | use strict; 25 | use warnings; 26 | use open ':std', IO => ':raw'; 27 | use File::Spec; 28 | use File::Temp 'tempfile'; 29 | use Getopt::Long qw(:config bundling); 30 | 31 | my $jpegtran = 'jpegtran'; 32 | my $metric = 'butteraugli'; 33 | my $home = glob '~'; 34 | my $maxbits = 3; 35 | GetOptions 'q' => \my $quiet, 'v' => \my $verbose, 'd=f' => \my $quality, 'b=i' => \$maxbits, 'n:i' => \my $norm, 36 | 'p=s' => \$jpegtran, 'c=s' => \$metric, 'r=s' => \my $reference, 'h|?' => \my $help; 37 | $verbose = defined $verbose; 38 | $jpegtran =~s /^~/$home/; 39 | $metric =~s /^~/$home/; 40 | $maxbits = 13 if $maxbits > 13; 41 | $maxbits = 0 if $maxbits < 0; 42 | $norm = 100 if defined $norm && $norm == 0; 43 | 44 | open STDOUT, '>', File::Spec->devnull if defined $quiet; 45 | 46 | @ARGV == 2 && !defined $help or die 'usage: jpegdropscan.pl [switches] inputfile outputfile 47 | JPEG lossy recompressor that removes least informative scans to reach a target 48 | quality 49 | Switches: 50 | -d N Maximum quality metric difference level (default: 0) 51 | -r path Path to reference image to use with quality metric evaluator 52 | (default: inputfile) 53 | -n [N] Use quality (N = best, 100 default) rather than distance (0 = best) 54 | -q Suppress all output 55 | -v Verbose output 56 | -p path Path to jpegtran (default: jpegtran) 57 | -c path Path to quality metric evaluator (default: butteraugli) 58 | -b 0-13 Maximum number of bit splits to test (default: 3) 59 | '; 60 | 61 | my ($fin, $fout) = @ARGV; 62 | $reference = $fin unless defined $reference; 63 | $fin =~s /^~/$home/; 64 | $fout =~s /^~/$home/; 65 | $reference =~s /^~/$home/; 66 | my ($tran, @best, $bestsize, $bestscore, $app0, $compare); 67 | my %colormap = ( 68 | 1 => 0, 2 => 1, 3 => 2, 4 => 3, # YCC(K) 69 | 82 => 0, 71 => 1, 66 => 2, # RGB 70 | 67 => 0, 77 => 1, 89 => 2, 75 => 3, # CMYK 71 | 114 => 0, 103 => 1, 98 => 2, # BG RGB 72 | 34 => 1, 35 => 2 # BG YCC 73 | ); 74 | my $mapcolor = \&mapcolor; 75 | undef $/; 76 | $| = 1; 77 | 78 | sub read_file($) { 79 | my ($file) = @_; 80 | open my $FILE, $file or die "Couldn't read file $file"; 81 | my $data = <$FILE>; 82 | close $FILE; 83 | $data; 84 | } 85 | 86 | sub write_file($@) { 87 | my $file = shift; 88 | open my $FILE, '>', $file or die "Couldn't write file $file"; 89 | print $FILE join '', @_; 90 | close $FILE; 91 | } 92 | 93 | sub tran(@) { 94 | `"$jpegtran" -optimize @_` or die; 95 | } 96 | 97 | sub wintran(@) { 98 | my (undef, $tmp) = tempfile SUFFIX => $$; 99 | system qq{"$jpegtran" -optimize @_ "$tmp"} or die; 100 | read_file $tmp; 101 | } 102 | 103 | sub metric($) { 104 | my $score = `"$metric" "$reference" "$_[0]"` or die; 105 | chop $score; 106 | $score; 107 | } 108 | 109 | sub mapcolor2($) { 110 | $_[0]; 111 | } 112 | 113 | sub mapcolor($) { 114 | if ($_[0] == 0) { 115 | $mapcolor = \&mapcolor2; 116 | return 0; 117 | } 118 | $colormap{$_[0]}; 119 | } 120 | 121 | sub scaninfo($) { 122 | my $file = substr $_[0], 2; 123 | $file = substr $file, $+[0] while $file =~ /\xFF\xD8.+?\xFF\xD9/s; # skip thumbnail(s) 124 | my @scans; 125 | while ($file =~ /\xFF\xDA/gs) { 126 | my $ns = ord substr $file, $+[0] + 2, 1; 127 | my $cs = join ' ', map &$mapcolor($_), unpack "(Cx)$ns", substr $file, $+[0] + 3, $ns * 2; 128 | my ($ss, $se, $ahal) = unpack 'C3', substr $file, $+[0] + 3 + $ns * 2, 3; 129 | push @scans, [$cs, $ss, $se, $ahal >> 4, $ahal & 3]; 130 | } 131 | @scans; 132 | } 133 | 134 | sub app0remove($) { 135 | my ($file) = @_; 136 | substr $file, 2, (2 + unpack 'n', substr $file, 4, 2), '' while "\xFF\xE0" eq substr $file, 2, 2; 137 | $file; 138 | } 139 | 140 | sub printscans(@) { 141 | join '', map sprintf("%s: %d %d %d %d;\n", @$_), @_; 142 | } 143 | 144 | sub tryscans($$) { 145 | my ($file, $scans) = @_; 146 | my (undef, $stmp) = tempfile SUFFIX => $$; 147 | write_file $stmp, $scans; 148 | my $data = &$tran('-scans', "\"$stmp\"", "\"$file\""); 149 | $data = app0remove $data if $app0; 150 | $data; 151 | } 152 | 153 | sub clone(@) { 154 | map [@$_], @_; 155 | } 156 | 157 | sub checkbest(@) { 158 | my $scans = printscans @_; 159 | print "\n$scans" if $verbose; 160 | my (undef, $tmp) = tempfile SUFFIX => $$; 161 | my $result = tryscans $fin, $scans; 162 | write_file $tmp, $result; 163 | my $score = metric $tmp; 164 | print $verbose ? "$score: " . length($result) . "\n" : '.'; 165 | if (&$compare($score, $quality)) { 166 | return -1; 167 | } elsif (length $result < $bestsize || length $result == $bestsize && !&$compare($bestscore, $score) && @_ <= @best) { 168 | @best = clone @_; 169 | $bestsize = length $result; 170 | $bestscore = $score; 171 | return 1; 172 | } 173 | 0; 174 | } 175 | 176 | sub inside($$$$) { 177 | $_[2] <= $_[0] <= $_[3] || $_[0] <= $_[2] <= $_[1]; 178 | } 179 | 180 | sub shavebits() { 181 | my @s = clone @best; 182 | for (1 .. $maxbits) { 183 | attempt: for (my $s = $#s; $s > 0; --$s) { 184 | my @lastscan = clone @s; 185 | next if $s[$s][4] != $_ - 1; 186 | if ($s[$s][3] != 0) { 187 | for my $t ($s + 1 .. $#s) { 188 | next attempt if $s[$s][0] eq $s[$t][0] && $s[$t][3] < $_ && inside $s[$s][1], $s[$s][2], $s[$t][1], $s[$t][2]; 189 | } 190 | splice @s, $s, 1; 191 | @s = @lastscan if checkbest(@s) == -1; 192 | } else { 193 | $s[$s][4] = $_; 194 | my $skip = 0; 195 | for my $t ($s + 1 .. $#s) { 196 | if ($s[$s][0] eq $s[$t][0] && $s[$t][3] < $_ && inside $s[$s][1], $s[$s][2], $s[$t][1], $s[$t][2]) { 197 | $skip = 1; 198 | last; 199 | } 200 | } 201 | if ($skip || checkbest(@s) == -1) { 202 | my ($p, $q) = @{$s[$s]}[1, 2]; 203 | if ($p < $q) { 204 | $s[$s][4] = $_ - 1; 205 | splice @s, $s + 1, 0, [$s[$s][0], $p, $q, $s[$s][3], $_]; 206 | subattempt: for (; $p < $q; ++$p) { 207 | $s[$s][2] = $p; 208 | $s[$s + 1][1] = $p + 1; 209 | for my $t ($s + 2 .. $#s) { 210 | next subattempt if $s[$s][0] eq $s[$t][0] && $s[$t][3] < $_ && (inside $s[$s + 1][1], $s[$s + 1][2], $s[$t][1], $s[$t][2] or inside $s[$s][1], $s[$s][2], $s[$t][1], $s[$t][2]); 211 | } 212 | next attempt if checkbest(@s) == 1; 213 | } 214 | } 215 | @s = @lastscan; 216 | } 217 | } 218 | } 219 | } 220 | } 221 | 222 | sub shavecoefs() { 223 | my @s = clone @best; 224 | for (my $c = 62; $c >= 0; --$c) { 225 | attempt: for (my $s = $#s; $s > 0; --$s) { 226 | next if $s[$s][2] != $c + 1; 227 | for my $t ($s + 1 .. $#s) { 228 | next attempt if $s[$s][0] eq $s[$t][0] && $s[$t][2] > $c && inside $s[$s][1], $s[$s][2], $s[$t][1], $s[$t][2]; 229 | } 230 | my @lastscan = clone @s; 231 | if ($s[$s][1] > $c) { 232 | splice @s, $s, 1; 233 | @s = @lastscan if checkbest(@s) == -1; 234 | } elsif ($s[$s][2] > $c) { 235 | $s[$s][2] = $c; 236 | @s = @lastscan if checkbest(@s) == -1; 237 | } 238 | } 239 | } 240 | } 241 | 242 | my $origdata = read_file $fin; 243 | die "$fin is not a valid JPEG file" if length($origdata) < 4 || "\xFF\xD8" ne substr $origdata, 0, 2; 244 | $app0 = "\xFF\xE0" eq substr $origdata, 2, 2; 245 | $maxbits = 10 if $maxbits > 10 && $origdata =~ /\xFF[\xC0-\xC3\xC5-\xC7\xC9-\xCB\xCD-\xCF]..\x08/s; 246 | $tran = `"$jpegtran" -? 2>&1` =~ /outputfile/ ? \&wintran : \&tran; 247 | my @scans = sort { 248 | my ($ap, $aa, $ab) = @$a; 249 | my ($bp, $ba, $bb) = @$b; 250 | !defined $ab || !defined $bb ? $ap cmp $bp : $ab <=> $bb || $ap cmp $bp 251 | } scaninfo $origdata; 252 | 253 | my @prev = (); 254 | for my $i (0 .. $#scans) { 255 | for (0 .. $#scans) { 256 | next if $i == $_; 257 | push @{$prev[$_]}, $i if $scans[$_][0] eq $scans[$i][0] && inside $scans[$i][1], $scans[$i][2], $scans[$_][1], $scans[$_][2] and $scans[$i][4] > $scans[$_][4] or $scans[$_][0] gt $scans[$i][0] && $scans[$_][2] >= $scans[$i][2]; 258 | } 259 | } 260 | 261 | my $i = -1; 262 | my @order = (); 263 | my %order = (); 264 | loop: while (@order < @scans) { 265 | $i = 0 if ++$i == @scans; 266 | next if defined $order{$i}; 267 | for (@{$prev[$i]}) { 268 | next loop unless defined $order{$_}; 269 | } 270 | push @order, $i; 271 | $order{$i} = 1; 272 | $i = -1; 273 | } 274 | @scans = @scans[@order]; 275 | 276 | for (my $i = 0; $i < @scans; ++$i) { 277 | my @s = @{$scans[$i]}; 278 | if ($s[1] == 0 && $s[2] > 0) { 279 | splice @scans, $i++, 1, [$s[0], 0, 0, $s[3], $s[4]]; 280 | splice @scans, $i++, 0, [$_, 1, $s[2], $s[3], $s[4]] for split ' ', $s[0]; 281 | } 282 | } 283 | my $origscore = metric $fin; 284 | my $insize = -s $fin; 285 | print printscans(@scans), "$origscore: $insize\n" if $verbose; 286 | $compare = $norm ? sub {$_[0] < $_[1]} : sub {$_[0] > $_[1]}; 287 | die "Initial quality $origscore is worse than desired quality." if &$compare($origscore, $quality); 288 | 289 | $bestsize = length $origdata; 290 | $bestscore = $origscore; 291 | @best = @scans; 292 | shavebits; 293 | shavecoefs; 294 | 295 | my $best = printscans @best; 296 | my $data = tryscans $fin, $best; 297 | print "\nBest scans:\n$best\nSize: $bestsize bytes\n"; 298 | printf "Change: %+.6f%%\n", ($bestsize / $insize - 1) * 100; 299 | print "Quality: $bestscore\n"; 300 | printf "Change: %+.6f\n", ($norm ? $bestscore - $origscore : $origscore - $bestscore); 301 | printf "Total Change: %+.6f%%\n", ($bestsize / (-s $reference) - 1) * 100 if $reference ne $fin; 302 | 303 | if ($bestsize && $bestsize <= $insize) { 304 | write_file $fout, $data; 305 | } elsif ($fin ne $fout) { 306 | write_file $fout, $origdata; 307 | } 308 | -------------------------------------------------------------------------------- /jpegultrascan.md: -------------------------------------------------------------------------------- 1 | # jpegultrascan 2 | JPEG lossless recompressor that tries all scan possibilities to minimize size 3 | 4 | ## Command line usage 5 | perl jpegultrascan.pl [switches] inputfile outputfile 6 | 7 | ## Switches 8 | -s Strip all extra markers 9 | -s some Strip only non-comment markers 10 | -i Allow multiple planes per DC scan, which may improve compression (incompatible with some software) 11 | -i -1 Disallow single scan DC components, which may be incompatible with some software 12 | -j Strip APP0 segment for 18-byte savings (generates non-compliant JPEG that may be incompatible with some 13 | software) 14 | -j 0-14 Strip APPn segment; specify multiple times to strip different segments (generates JPEG that may be 15 | incompatible with some software) 16 | -a Use arithmetic coding (unsupported by most software; jpegtran support required) 17 | -b 0-13 Maximum number of bit splits to test (default: 3) 18 | -t [N] Number of simultaneous processes (default: 8 if specified, 1 otherwise) 19 | -q Suppress all output 20 | -v Verbose output 21 | -p path Path to jpegtran (default: jpegtran) 22 | -o path Path to other jpegtran (default: jpegtran) 23 | 24 | ## Requirements 25 | - [Perl](https://www.perl.org/) 26 | - jpegtran from [libjpeg](https://jpegclub.org/reference/reference-sources/), [libjpeg-turbo](https://github.com/libjpeg-turbo/libjpeg-turbo), and/or [mozjpeg](https://github.com/mozilla/mozjpeg) 27 | 28 | ## Notes 29 | Jpegultrascan is modeled after [jpegrescan](https://github.com/kud/jpegrescan), but improves compression over jpegrescan by 5-10% by performing an exhaustive search. Resulting optimized images may have many more scans than progressive encoding, though there should be no noticeable difference on modern decoders. 30 | 31 | Due to the exhaustive search, recompression takes longer than jpegrescan. Higher values of `-b` results in longer compression times. 32 | 33 | Optimal compression is achieved by specifying the mozjpeg version of jpegtran for the `-o` switch. However, mozjpeg is slower and buggy with certain scan configurations, so IJG jpegtran is recommended for the `-p` switch. 34 | 35 | `-i` generates files that are incompatible with some software such as Photoshop and Opera <= 11.61. `-i -1` generates files that are compatible with IPP JPEG. 36 | 37 | Jpegultrascan is compatible with arbitrary numbers of channels, including CMYK, and ICC profiles. 38 | 39 | ## Author 40 | Aaron Kaluszka <> 41 | -------------------------------------------------------------------------------- /jpegultrascan.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | =head1 NAME 3 | jpegultrascan 4 | =head1 DESCRIPTION 5 | JPEG lossless recompressor that tries all scan possibilities to minimize size 6 | =head1 VERSION 7 | 1.4.0 2024-04-19 8 | =head1 LICENSE 9 | Copyright 2015-2024 Aaron Kaluszka 10 | 11 | Licensed under the Apache License, Version 2.0 (the "License"); 12 | you may not use this file except in compliance with the License. 13 | You may obtain a copy of the License at 14 | 15 | http://www.apache.org/licenses/LICENSE-2.0 16 | 17 | Unless required by applicable law or agreed to in writing, software 18 | distributed under the License is distributed on an "AS IS" BASIS, 19 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 20 | See the License for the specific language governing permissions and 21 | limitations under the License. 22 | =cut 23 | 24 | use strict; 25 | use warnings; 26 | use open ':std', IO => ':raw'; 27 | use File::Spec; 28 | use File::Temp 'tempfile'; 29 | use Getopt::Long qw(:config bundling); 30 | use constant MAXCOEF => 63; 31 | 32 | my $maxbits = 3; 33 | my $threads = 1; 34 | my $jpegtran = my $jpegtran2 = 'jpegtran'; 35 | my $home = glob '~'; 36 | GetOptions 'q' => \my $quiet, 'v' => \my $verbose, 'i:i' => \my $incompat, 'j:i' => \my @app, 's' => \my $strip, 'a' => \my $arith, 37 | 'p=s' => \$jpegtran, 'o=s' => \$jpegtran2, 'b=i' => \$maxbits, 't:i' => \$threads, 'h|?' => \my $help; 38 | my @strip = my @strip2 = ('-copy', defined $strip ? $strip eq 'some' ? 'comments' : 'none' : 'all'); 39 | $arith = defined $arith ? '-arithmetic' : ''; 40 | $verbose = defined $verbose; 41 | $incompat = defined $incompat ? $incompat == 0 ? 1 : $incompat : 0; 42 | $threads = 8 if $threads < 1; 43 | $maxbits = 13 if $maxbits > 13; 44 | $maxbits = 0 if $maxbits < 0; 45 | $jpegtran =~s /^~/$home/; 46 | $jpegtran2 =~s /^~/$home/; 47 | 48 | open STDOUT, '>', File::Spec->devnull if defined $quiet; 49 | open my $STDOUT, '>&STDOUT'; 50 | 51 | @ARGV == 2 && !defined $help or die 'usage: jpegultrascan.pl [switches] inputfile outputfile 52 | JPEG lossless recompressor that tries all scan possibilities to minimize size 53 | Switches: 54 | -s Strip all extra markers 55 | -s some Strip only non-comment markers 56 | -i Allow multiple planes per DC scan, which may be incompatible with 57 | some software 58 | -i -1 Disallow single scan DC components, which may be incompatible with 59 | some software 60 | -j Strip APP0 segment for 18-byte savings (generates non-compliant JPEG 61 | that may be incompatible with some software) 62 | -j 0-14 Strip APPn segment; specify multiple times to strip different 63 | segments (generates JPEG that may be incompatible with some software) 64 | -a Use arithmetic coding (unsupported by most software; jpegtran support 65 | required) 66 | -b 0-13 Maximum number of bit splits to test (default: 3) 67 | -t [N] Number of simultaneous processes (default: 8 if specified, 68 | 1 otherwise) 69 | -q Suppress all output 70 | -v Verbose output 71 | -p path Path to jpegtran (default: jpegtran) 72 | -o path Path to other jpegtran (default: jpegtran) 73 | '; 74 | 75 | my ($fin, $fout) = @ARGV; 76 | $fin =~s /^~/$home/; 77 | $fout =~s /^~/$home/; 78 | my $insize = -s $fin; 79 | my (undef, $ftmp) = tempfile; 80 | my (undef, $jtmp) = tempfile; 81 | my $maxperfile = 60; 82 | my $minchunk = $threads; 83 | my (%sizes, $planes, %optimal, %optimal2, @scans, %dcsize, %dcscans, @acsize, @acscans, $acallsize, $acallscans, $width, $width2); 84 | my ($bestsize, $best) = (~0, ''); 85 | my ($tran, $tran2); 86 | undef $/; 87 | $| = 1; 88 | 89 | sub read_file($) { 90 | my ($file) = @_; 91 | open my $FILE, $file or die "Couldn't read file $file"; 92 | my $data = <$FILE>; 93 | close $FILE; 94 | $data; 95 | } 96 | 97 | sub write_file($@) { 98 | my $file = shift; 99 | open my $FILE, '>', $file or die "Couldn't write file $file"; 100 | print $FILE join '', @_; 101 | close $FILE; 102 | } 103 | 104 | sub tran(@) { 105 | `"$jpegtran" -optimize @_` or die; 106 | } 107 | 108 | sub wintran(@) { 109 | my (undef, $tmp) = tempfile SUFFIX => $$; 110 | system qq{"$jpegtran" -optimize @_ "$tmp"} or die; 111 | my $data = read_file $tmp; 112 | unlink $tmp; 113 | $data; 114 | } 115 | 116 | sub scansizes($) { 117 | my ($file) = @_; 118 | my @sizes; 119 | my $scanstart = 0; 120 | my $nextoff = 0; 121 | while ($file =~ /\xFF+(.)/gs) { 122 | next if $+[0] < $nextoff + 2; 123 | my $type = ord $1; 124 | next unless $type; 125 | my $tagstart = $-[0] < $nextoff ? $nextoff : $-[0]; 126 | my $len = ($type == 216 || $type == 217 ? 0 : unpack 'n', substr $file, $+[0], 2) + $+[0] - $tagstart; 127 | $nextoff = $tagstart + $len; 128 | if ($scanstart) { 129 | $sizes[$#sizes] += $tagstart - $scanstart; 130 | last if $type == 217; 131 | push @sizes, $len; 132 | $scanstart = 0; 133 | } elsif (!@sizes && 192 <= $type <= 207 && $type != 196 && $type != 200 && $type != 204) { 134 | push @sizes, 0; 135 | } elsif (@sizes) { 136 | $sizes[$#sizes] += $len; 137 | } 138 | $scanstart = $tagstart + $len if $type == 218; 139 | } 140 | @sizes; 141 | } 142 | 143 | sub transcan($$) { 144 | my ($start, $end) = @_; 145 | my (undef, $tmp) = tempfile SUFFIX => $$; 146 | my @sizes; 147 | for my $i ($start .. $end) { 148 | write_file $tmp, @{$scans[$i]}; 149 | my $data = &$tran('-scans', "\"$tmp\"", $arith, "\"$jtmp\""); 150 | if (length $data == 0) { 151 | print STDERR "\nNo data returned for:\n", join '', @{$scans[$i]}; 152 | next; 153 | } 154 | my @sizesi = scansizes $data; 155 | if ($#sizesi != $#{$scans[$i]}) { 156 | print STDERR "\nIncorrect encoding for:\n", join '', @{$scans[$i]}; 157 | next; 158 | } 159 | if ($verbose) { 160 | for (0 .. $#sizesi) { 161 | my $scan = @{$scans[$i]}[$_]; 162 | unless (defined $sizes{$scan}) { 163 | $sizes{$scan} = $sizesi[$_]; 164 | chop $scan; 165 | printf $STDOUT "%-${width}s %${width2}d\n", $scan, $sizesi[$_]; 166 | } 167 | } 168 | } else { 169 | print $STDOUT '.'; 170 | } 171 | push @sizes, $i, @sizesi; 172 | } 173 | unlink $tmp; 174 | @sizes; 175 | } 176 | 177 | sub pipefork() { 178 | pipe my $parent, my $child or die "Couldn't pipe\n"; 179 | my $pid = fork; 180 | die "fork failed: $!" unless defined $pid; 181 | if ($pid) { 182 | close $child; 183 | } else { 184 | close $parent; 185 | close STDOUT; 186 | open STDOUT, '>&=', fileno $child or die "Couldn't open STDOUT\n"; 187 | } 188 | ($parent, $pid); 189 | } 190 | 191 | sub doscans() { 192 | if ($threads == 1 || $#scans < $minchunk) { 193 | my @sizes = transcan 0, $#scans; 194 | unless ($verbose) { 195 | for (my $i = 0; $i < $#sizes; ++$i) { 196 | $sizes{$_} = $sizes[++$i] for @{$scans[$sizes[$i]]}; 197 | } 198 | } 199 | } else { 200 | my $chunk = int @scans / $threads; 201 | $chunk = $minchunk if $chunk < $minchunk; 202 | my $end = scalar @scans; 203 | my @fh; 204 | for (my $start = 0; $start < $end; $start += $chunk) { 205 | my ($fh, $pid) = pipefork; 206 | unless ($pid) { 207 | print join ',', transcan $start, ($start + $chunk < $end - $minchunk ? $start + $chunk : $end) - 1; 208 | exit; 209 | } 210 | push @fh, $fh; 211 | } 212 | for (@fh) { 213 | my @sizes = split ',', <$_>; 214 | for (my $i = 0; $i < $#sizes; ++$i) { 215 | $sizes{$_} = $sizes[++$i] for @{$scans[$sizes[$i]]}; 216 | } 217 | } 218 | } 219 | @scans = () 220 | } 221 | 222 | sub queuescans(@) { 223 | push @scans, \@_; 224 | } 225 | 226 | sub queuescansmulti(@) { 227 | my (@dc, @ac); 228 | for (my $i = 0; $i < @_; ++$i) { 229 | if (@dc + @ac > $maxperfile) { 230 | do { 231 | pop @ac; 232 | --$i; 233 | } while $ac[$#ac] !~ / 0;\n$/; 234 | queuescans @dc, @ac; 235 | @ac = (); 236 | } 237 | if ($_[$i] =~ /: 0 0/) { 238 | push @dc, splice @_, $i, 1; 239 | --$i; 240 | } else { 241 | push @ac, $_[$i]; 242 | } 243 | } 244 | queuescans @dc, @ac if @ac > 0; 245 | } 246 | 247 | sub generatebitscans($$$$) { 248 | my ($plane, $a, $b, $numbits) = @_; 249 | my @scans = "$plane: $a $b 0 $numbits;\n"; 250 | for (my $i = $numbits; $i > 0; --$i) { 251 | push @scans, "$plane: $a $b $i " . ($i - 1) . ";\n"; 252 | } 253 | @scans; 254 | } 255 | 256 | sub generatedcscans($) { 257 | my ($plane) = @_; 258 | my $allplanes = join ' ', 0 .. $planes; 259 | my $dummy; 260 | if ($plane ne $allplanes) { 261 | $dummy = $allplanes; 262 | $dummy =~s /$_ ?// for split ' ', $plane; 263 | $dummy =~s /^(.*?) ?$/$1: 0 0 0 9;\n/; 264 | } 265 | for (0 .. $maxbits) { 266 | my @scans = generatebitscans $plane, 0, 0, $_; 267 | push @scans, $dummy if $dummy; 268 | queuescans @scans; 269 | } 270 | } 271 | 272 | sub generateacscans($) { 273 | my ($plane) = @_; 274 | my $dummy = join(' ', 0 .. $planes) . ": 0 0 0 9;\n"; 275 | for (0 .. MAXCOEF - 1) { 276 | for my $offset (0 .. ($_ < MAXCOEF - 1 - $_ ? $_ : MAXCOEF - 1 - $_)) { 277 | for (my $numbits = 0; $numbits <= $maxbits; ++$numbits) { 278 | my @scans = $dummy; 279 | push @scans, generatebitscans $plane, 1, $offset, $numbits if $offset > 0; 280 | my $i = $offset + 1; 281 | for (; $i + $_ < MAXCOEF; $i += $_ + 1) { 282 | push @scans, generatebitscans $plane, $i, $i + $_, $numbits; 283 | } 284 | push @scans, generatebitscans $plane, $i, MAXCOEF, $numbits if $i <= MAXCOEF; 285 | @scans <= $maxperfile ? queuescans @scans : queuescansmulti @scans; 286 | } 287 | } 288 | } 289 | } 290 | 291 | sub choosebest($$$$) { 292 | my ($leftsize, $left, $rightsize, $right) = @_; 293 | return if !$leftsize && !$rightsize; 294 | return ($leftsize, $left) if !$rightsize || $leftsize && $leftsize < $rightsize; 295 | return ($rightsize, $right) if !$leftsize || $rightsize && $leftsize > $rightsize || scalar(() = $left =~ /\n/g) > scalar(() = $right =~ /\n/g); 296 | ($leftsize, $left); 297 | } 298 | 299 | sub trybitsplits($$$$$); 300 | sub trybitsplits($$$$$) { 301 | my ($plane, $a, $b, $c, $d) = @_; 302 | my $key = "$plane $a $b $c $d"; 303 | unless ($optimal2{$key}) { 304 | my $minscans = "$plane: $a $b $c $d;\n"; 305 | my $minsize = $sizes{$minscans}; 306 | for ($a .. $b - 1) { 307 | my ($asize, $ascans) = trybitsplits $plane, $a, $_, $c, $d; 308 | my ($bsize, $bscans) = trybitsplits $plane, $_ + 1, $b, $c, $d; 309 | ($minsize, $minscans) = choosebest $asize + $bsize, $ascans . $bscans, $minsize, $minscans; 310 | } 311 | $optimal2{$key} = [$minsize, $minscans]; 312 | } 313 | @{$optimal2{$key}}; 314 | } 315 | 316 | sub trysplits($$$); 317 | sub trysplits($$$) { 318 | my ($plane, $a, $b) = @_; 319 | my $key = "$plane $a $b"; 320 | unless ($optimal{$key}) { 321 | my ($minsize, $minscans) = (~0, ''); 322 | for (0 .. $maxbits) { 323 | my ($allsize, $allscans) = trybitsplits $plane, $a, $b, 0, $_; 324 | for (my $i = $_; $i > 0; --$i) { 325 | my ($size, $scans) = trybitsplits $plane, $a, $b, $i, $i - 1; 326 | $allsize += $size; 327 | $allscans .= $scans; 328 | } 329 | ($minsize, $minscans) = choosebest $allsize, $allscans, $minsize, $minscans; 330 | } 331 | for ($a .. $b - 1) { 332 | my ($asize, $ascans) = trysplits $plane, $a, $_; 333 | my ($bsize, $bscans) = trysplits $plane, $_ + 1, $b; 334 | ($minsize, $minscans) = choosebest $asize + $bsize, $ascans . $bscans, $minsize, $minscans; 335 | } 336 | $optimal{$key} = [$minsize, $minscans]; 337 | } 338 | @{$optimal{$key}}; 339 | } 340 | 341 | sub appremove($$) { 342 | my ($file, $n) = @_; 343 | my $tag = pack 'CC', 255, 224 + $n; 344 | while ($tag eq substr $file, 2, 2) { 345 | my $size = 2 + unpack 'n', substr $file, 4, 2; 346 | substr $file, 2, $size, ''; 347 | print $verbose ? "\nRemoved $size APP$n bytes.\n" : '.'; 348 | } 349 | $file; 350 | } 351 | 352 | sub partitionscans($@); 353 | sub partitionscans($@) { 354 | my $offset = shift; 355 | my ($dcallsize, $dcallscans) = (0, ''); 356 | for (@_) { 357 | unless (defined $dcsize{$_}) { 358 | generatedcscans $_; 359 | doscans; 360 | ($dcsize{$_}, $dcscans{$_}) = trysplits $_, 0, 0; 361 | } 362 | $dcallsize += $dcsize{$_}; 363 | $dcallscans .= $dcscans{$_}; 364 | } 365 | ($bestsize, $best) = choosebest $dcallsize + $acallsize, $dcallscans . $acallscans, $bestsize, $best; 366 | my @all = map "$_;\n", @_; 367 | for (@all) { 368 | unless (defined $sizes{$_}) { 369 | queuescans @all; 370 | doscans; 371 | last; 372 | } 373 | } 374 | my $allsize = 0; 375 | for (@all) { 376 | $allsize += $sizes{$_} if $sizes{$_}; 377 | } 378 | ($bestsize, $best) = choosebest $allsize, join('', @all), $bestsize, $best; 379 | for my $i ($offset .. $#_) { 380 | for ($i + 1 .. $#_) { 381 | $_[$offset] =~ /(\d+)$/; 382 | next if $_[$_] < $1; 383 | my @newpartition = @_; 384 | $newpartition[$i] .= ' ' . splice @newpartition, $_, 1; 385 | partitionscans $i, @newpartition; 386 | } 387 | } 388 | } 389 | 390 | my $data = read_file $fin; 391 | $maxbits = 10 if $maxbits > 10 && $data =~ /\xFF[\xC0-\xC3\xC5-\xC7\xC9-\xCB\xCD-\xCF]..\x08/s; 392 | my $hasicc = $data =~ /\xFF\xE2(..)ICC_PROFILE/s && substr($data, $+[0], unpack 'n', $1) !~ /desc.+sRGB/s; 393 | $data = `"$jpegtran" -? 2>&1`; 394 | $tran = $data =~ /outputfile/ ? \&wintran : \&tran; 395 | $strip[1] = $data =~ /copy icc/ ? 'icc' : 'all' if $hasicc && $strip[1] ne 'all'; 396 | $data = `"$jpegtran2" -? 2>&1`; 397 | $strip2[1] = $data =~ /copy icc/ ? 'icc' : 'all' if $hasicc && $strip2[1] ne 'all'; 398 | if ($data =~ /outputfile/) { 399 | $data = `"$jpegtran2" -v @strip2 -optimize "$fin" "$jtmp" 2>&1`; 400 | $tran2 = \&wintran; 401 | } else { 402 | open my $OLDERR, '>&', STDERR; 403 | open STDERR, '>', $ftmp; 404 | open my $TRAN, '-|', $jpegtran2, '-v', @strip2, '-optimize', $fin; 405 | $data = <$TRAN>; 406 | close $TRAN; 407 | open STDERR, '>&', $OLDERR; 408 | write_file $jtmp, $data; 409 | $data = read_file $ftmp; 410 | $tran2 = \&tran; 411 | } 412 | $data =~ /components=(\d+)/ or die "Couldn't read file"; 413 | $planes = $1 - 1; 414 | $width = ($planes + 1) * 2 + 10; 415 | $width2 = length $insize; 416 | 417 | for (0 .. $planes) { 418 | print "Calculating sizes of AC scans, plane $_\n"; 419 | generateacscans $_; 420 | doscans; 421 | print "\nSearching for best AC scan, plane $_\n"; 422 | ($acsize[$_], $acscans[$_]) = trysplits $_, 1, MAXCOEF; 423 | $acallsize += $acsize[$_]; 424 | $acallscans .= $acscans[$_]; 425 | print "Best AC scan, plane $_:\n$acscans[$_]Size: $acsize[$_]\n\n" if $verbose; 426 | } 427 | 428 | print "Calculating sizes and searching for best DC scan\n"; 429 | if ($incompat > 0 && $planes > 1) { 430 | partitionscans 0, 0 .. $planes; 431 | } else { 432 | partitionscans $planes + 1, 0 .. $planes if $planes > 0 && $incompat >= 0; 433 | partitionscans 2, join ' ', 0 .. $planes; 434 | } 435 | if ($verbose) { 436 | my $dcallscans = $best; 437 | $dcallscans =~ s/$acallscans//; 438 | print "\nBest DC scan:\n${dcallscans}Size: ", $bestsize - $acallsize, "\n" if $verbose && $dcallscans ne $best; 439 | } 440 | 441 | $best = join "\n", sort { 442 | my $pattern = qr/^([^:]*)(?:: (\d+) (\d+) \d+ (\d+))?/; 443 | my ($ap, $aa, $ab, $ad) = $a =~ /$pattern/g; 444 | my ($bp, $ba, $bb, $bd) = $b =~ /$pattern/g; 445 | !defined $ab || !defined $bb ? $ap cmp $bp : $ab <=> $bb || $ap cmp $bp 446 | } split "\n", $best; 447 | 448 | my @best = map {[/^([^:]*)(?:: (\d+) (\d+) \d+ (\d+))?/g]} split "\n", $best; 449 | 450 | my @prev = (); 451 | for my $i (0 .. $#best) { 452 | for my $j (0 .. $#best) { 453 | next if $i == $j; 454 | push @{$prev[$j]}, $i if ( 455 | ($best[$j][0] eq $best[$i][0] && ($best[$i][1] <= $best[$j][1] <= $best[$i][2] || $best[$j][1] <= $best[$i][1] <= $best[$j][2]) && $best[$i][3] > $best[$j][3]) 456 | || ($best[$j][0] gt $best[$i][0] && $best[$j][2] >= $best[$i][2]) 457 | ); 458 | } 459 | } 460 | 461 | my $i = -1; 462 | my @bestout = (); 463 | my %bestout = (); 464 | loop: while(@bestout < @best) { 465 | $i = 0 if ++$i == @best; 466 | next if defined $bestout{$i}; 467 | for (@{$prev[$i]}) { 468 | next loop unless defined $bestout{$_}; 469 | } 470 | push @bestout, $i; 471 | $bestout{$i} = 1; 472 | $i = -1; 473 | } 474 | $best = join "\n", (split "\n", $best)[@bestout]; 475 | 476 | write_file $ftmp, $best; 477 | $data = &$tran('-scans', "\"$ftmp\"", $arith, @strip, "\"$jtmp\""); 478 | $data = appremove $data, $_ for @app; 479 | 480 | if ($jpegtran ne $jpegtran2) { 481 | $jpegtran = $jpegtran2; 482 | my $data2 = &$tran2('-scans', "\"$ftmp\"", $arith, @strip2, "\"$jtmp\""); 483 | $data2 = appremove $data2, $_ for @app; 484 | $data = $data2 if length $data2 && length $data2 < length $data; 485 | } 486 | 487 | my $size = length $data; 488 | print "\nBest scans:\n$best\nSize: $size bytes\n"; 489 | printf "Change: %+.6f%%\n", ($size / $insize - 1) * 100; 490 | 491 | if ($size && $size <= $insize) { 492 | write_file $fout, $data; 493 | } elsif ($fin ne $fout) { 494 | write_file $fout, read_file $fin; 495 | } 496 | unlink $ftmp, $jtmp; 497 | --------------------------------------------------------------------------------