webp2png.pl 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # Date: 10 April 2021
  4. # https://github.com/trizen
  5. # Convert WEBP images to PNG, using the `dwebp` tool from "libwebp".
  6. # The original WEBP files are deleted.
  7. use 5.036;
  8. use File::Find qw(find);
  9. use Getopt::Long qw(GetOptions);
  10. my $dwebp_cmd = "dwebp"; # `dwebp` command
  11. my $use_exiftool = 0; # true to use `exiftool` instead of `File::MimeInfo::Magic`
  12. `$dwebp_cmd -h`
  13. or die "Error: `$dwebp_cmd` tool from 'libwebp' is not installed!\n";
  14. sub webp2png ($file) {
  15. my $orig_file = $file;
  16. my $png_file = $file;
  17. if ($png_file =~ s/\.webp\z/.png/i) {
  18. ## ok
  19. }
  20. else {
  21. $png_file .= '.png';
  22. }
  23. if (-e $png_file) {
  24. warn "[!] File <<$png_file>> already exists...\n";
  25. next;
  26. }
  27. system($dwebp_cmd, $orig_file, '-o', $png_file);
  28. if ($? == 0 and (-e $png_file) and ($png_file ne $orig_file)) {
  29. unlink($orig_file);
  30. }
  31. else {
  32. return;
  33. }
  34. return 1;
  35. }
  36. sub determine_mime_type ($file) {
  37. if ($file =~ /\.webp\z/i) {
  38. return "image/webp";
  39. }
  40. if ($use_exiftool) {
  41. my $res = `exiftool \Q$file\E`;
  42. $? == 0 or return;
  43. defined($res) or return;
  44. if ($res =~ m{^MIME\s+Type\s*:\s*(\S+)}mi) {
  45. return $1;
  46. }
  47. return;
  48. }
  49. require File::MimeInfo::Magic;
  50. File::MimeInfo::Magic::magic($file);
  51. }
  52. my %types = (
  53. 'image/webp' => {
  54. call => \&webp2png,
  55. }
  56. );
  57. GetOptions('exiftool!' => \$use_exiftool,)
  58. or die "Error in command-line arguments!";
  59. @ARGV or die <<"USAGE";
  60. usage: perl $0 [options] [dirs | files]
  61. options:
  62. --exiftool : use `exiftool` to determine the MIME type (default: $use_exiftool)
  63. USAGE
  64. find(
  65. {
  66. no_chdir => 1,
  67. wanted => sub {
  68. (-f $_) || return;
  69. my $type = determine_mime_type($_) // return;
  70. if (exists $types{$type}) {
  71. $types{$type}{call}->($_);
  72. }
  73. }
  74. } => @ARGV
  75. );
  76. say ":: Done!";