-
Notifications
You must be signed in to change notification settings - Fork 33
/
gif2webp.pl
103 lines (76 loc) · 2.08 KB
/
gif2webp.pl
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#!/usr/bin/perl
# Author: Trizen
# Date: 14 October 2023
# https://github.com/trizen
# Convert GIF animations to WEBP animations, using the `gif2webp` tool from "libwebp".
# The original GIF files are deleted.
use 5.036;
use File::Find qw(find);
use Getopt::Long qw(GetOptions);
my $gif2webp_cmd = "gif2webp"; # `gif2webp` command
my $use_exiftool = 0; # true to use `exiftool` instead of `File::MimeInfo::Magic`
`$gif2webp_cmd -h`
or die "Error: `$gif2webp_cmd` tool from 'libwebp' is not installed!\n";
sub gif2webp ($file) {
my $orig_file = $file;
my $webp_file = $file;
if ($webp_file =~ s/\.gif\z/.webp/i) {
## ok
}
else {
$webp_file .= '.webp';
}
if (-e $webp_file) {
warn "[!] File <<$webp_file>> already exists...\n";
next;
}
system($gif2webp_cmd, '-lossy', $orig_file, '-o', $webp_file);
if ($? == 0 and (-e $webp_file) and ($webp_file ne $orig_file)) {
unlink($orig_file);
}
else {
return;
}
return 1;
}
sub determine_mime_type ($file) {
if ($file =~ /\.gif\z/i) {
return "image/gif";
}
if ($use_exiftool) {
my $res = `exiftool \Q$file\E`;
$? == 0 or return;
defined($res) or return;
if ($res =~ m{^MIME\s+Type\s*:\s*(\S+)}mi) {
return $1;
}
return;
}
require File::MimeInfo::Magic;
File::MimeInfo::Magic::magic($file);
}
my %types = (
'image/gif' => {
call => \&gif2webp,
},
);
GetOptions('exiftool!' => \$use_exiftool,)
or die "Error in command-line arguments!";
@ARGV or die <<"USAGE";
usage: $0 [options] [dirs | files]
options:
--exiftool : use `exiftool` to determine the MIME type (default: $use_exiftool)
USAGE
find(
{
no_chdir => 1,
wanted => sub {
(-f $_) || return;
my $type = determine_mime_type($_) // return;
if (exists $types{$type}) {
$types{$type}{call}->($_);
}
}
} => @ARGV
);
say ":: Done!";