Skip to content

Instantly share code, notes, and snippets.

@animaux
Created June 22, 2023 10:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save animaux/25312937a23a45dff4e126937d935ebd to your computer and use it in GitHub Desktop.
Save animaux/25312937a23a45dff4e126937d935ebd to your computer and use it in GitHub Desktop.
#!/usr/bin/perl
# Perl Script to convert SVG images including PNG24 encoded images to SVG with PNG8 while retaining transparency
# Requirements:
# sudo cpan Image::Magick
use strict;
use warnings;
use Image::Magick;
use MIME::Base64 qw< encode_base64 decode_base64 >;
# Usage
# [sudo] perl svg-png24-8.pl input.svg
# Function to convert PNG24 to PNG8
sub process_image {
my ($png24_base64) = @_;
#print "INPUT: " . substr($png24_base64,0,128) . "…\n\n";
my $image = Image::Magick->new;
my $decoded = MIME::Base64::decode_base64($png24_base64);
$image->Read(blob => $decoded);
# Set image format to PNG8
$image->Set(magick => 'PNG8');
# Convert image to RGB?
# $image->Quantize(colorspace => 'RGB');
# print $image->Identify;
# Get the resulting PNG8 image as binary blob
my $png8_blob = $image->ImageToBlob();
#print "png8_blob: " . substr($png8_blob,0,128) . "…\n\n";
# Encode the PNG8 blob as base64
my $png8_base64 = encode_base64($png8_blob);
#print "png8_base64: " . substr($png8_base64,0,128) . "…\n\n";
return $png8_base64;
}
# Check if a file name argument is provided
if (@ARGV != 1) {
die "Usage: perl svg-png24-8.pl <input_file>\n";
}
# Input file name
my $input_file = $ARGV[0];
# Output file name with "-png8" appended
my $output_file = $input_file;
$output_file =~ s/(\.[^.]+)?$/-png8$1/;
# Regular expression pattern to match the desired strings
my $pattern = qr/"data:img\/png;base64,([^"]*)"/;
# Read input file
open my $input_fh, '<', $input_file or die "Failed to open input file: $!";
# Process the file line by line
my $output = "";
while (my $line = <$input_fh>) {
chomp $line;
# Check if the line matches the pattern
if ($line =~ $pattern) {
#print "\n\nLINE: " . substr($line,0,128);
# Replace matched strings with processed result
my $replacement = eval "process_image(\$1)";
if ($@) {
warn "Error during evaluation: $@";
$replacement = $1; # Use original string as replacement in case of error
}
# reintroduce header and quotes
$replacement = '"data:image/png;base64,' . $replacement . '"';
$line =~ s/$pattern/$replacement/;
}
$output .= $line . "\n";
}
# Close input file
close($input_fh);
# Save the modified content to the output file
open(my $output_fh, ">", $output_file) or die "Cannot open output file: $!";
print $output_fh $output;
close($output_fh);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment