Skip to content

Instantly share code, notes, and snippets.

@Mortimerp9
Created November 8, 2012 02:08
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 Mortimerp9/4036108 to your computer and use it in GitHub Desktop.
Save Mortimerp9/4036108 to your computer and use it in GitHub Desktop.
This is a very rough perl script that will go through a css file and find the possible rgba statements, it will then insert a fallback hex value before the rgba statement. As this was tailored to a particular use case, it only deals with background color
#!/usr/bin/perl
use strict;
sub min {
my ($a, $b) = @_;
if($a < $b) { return $a; }
else { return $b; }
}
sub conv {
my ($col, $alpha) = @_;
return min(1, (($alpha)*$col/255 + (1-$alpha)));
}
sub convert {
my ($r,$g,$b,$a) = @_;
return sprintf('#%x%x%x',
255*conv($r, $a),
255*conv($g, $a),
255*conv($b, $a));
}
while(<>) {
chomp;
my $line = $_;
if($line =~ /(background(-color)?: ?rgba\(([0-9]+), ?([0-9]+), ?([0-9]+), ?([0-9.]+)\);)/) {
my $hex = convert($3, $4, $5, $6);
my $pos = index($line, $1);
$line= substr($line, 0, $pos)."background-color: $hex; ".substr($line, $pos);
}
if($line =~ /(border(-[^:]*)?:([^;]*)?rgba\(([0-9]+), ?([0-9]+), ?([0-9]+), ?([0-9.]+)\);)/) {
my $hex = convert($4, $5, $6, $7);
my $pos = index($line, $1);
$line = substr($line, 0, $pos)."border$2: $3 $hex; ".substr($line, $pos);
}
print $line . "\n";
}
@Mortimerp9
Copy link
Author

usage: perl rgbafallback.pl mycss.css > bettercss.css

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment