Last Updated: February 25, 2016
·
1.445K
· geetotes

Responsive, progressive JPEGs made easy with Perl

I've recently been working on a quick Perl script to help me create images for responsive websites. The script runs atop ImageMagick, and can create more than just jpegs.

Basically it works by taking an array of sizes (based off Twitter Bootstrap's @media-query values):

@sizes = ("480", "768", "992", "1200");

Using this array (and a file in @fileList), a file gets resized and converted into a progressive JPG (for quick loading).

foreach (@fileList) {
  print "Reading $_\n";
  my $p = new Image::Magick;
  my $filename = $_;
  $p->Read($filename);
  foreach (@sizes) {
    my $new = $p->Clone;
    $new->Resize(geometry=>$_);
    (my $without_extension = $filename) =~ s/\.[^.]+$//;
    $new_filename = $without_extension."-".$_.".jpg";
    $new->Write(filename => $new_filename, interlace=> plane, quality => 85);
    #make @2X for retina
    $new->Resize(geometry=>$_*2);
    $retina_filename = $without_extension."-".$_."\@2X.jpg";
    $new->Write(filename => $retina_filename, interlace=> plane, quality => 85);
  }
}

Using this snippet (see full gist for more code), it's pretty easy to generate responsive images as part of either a pre-deploy checklist or CI process.