Perl resources, modules, and sample code

Convert image sources to data URI with Perl: img2data

Wednesday, 16 March 2011—subject to ongoing, unnanounced updates

Modern Perl Modern Perl at Powell’s, Modern Perl at Barnes and Noble, Modern Perl at Amazon.com, or download Modern Perl for free and then recommend it to your friends, write a great review, or otherwise spread the word.

Data URI scheme. img2data on github. Current version–

#!/usr/bin/env perl
use warnings;
use strict;
use MIME::Base64;
use Image::ExifTool;
use Path::Class qw( file );

#---------------------------------------------------------
my $max_k = 5;

my $img = file(shift || die "Give me an image file.\n");

-e $img || die "Can't find $img, tough guy.\n";

die "That's too big for this kind of thing; ${max_k}K max.\n"
    if -s $img > $max_k * 1_024;

my $exif = Image::ExifTool->new;

my $info = $exif->ImageInfo($img->stringify);

my $src = sprintf "data:%s;base64,%s",
    $info->{MIMEType},
    encode_base64($img->slurp);

$src =~ s/\R//g;

print $src, $/;

exit 0;

__DATA__

And this–

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAMAAAD04JH5AAAAA 3NCSVQICAjb4U/gAAAAYFBMVEX////MAGY9MZbogwogjLJxpGAgjLJxpGAgjLLMAGbogwro gwo9MZbMAGY9MZbMAGYgjLLogwpxpGBxpGBxpGDMAGZxpGA9MZY9MZbogwpxpGDogwrMAGY 9MZZxpGDMAGaMha1WAAAAIHRSTlMA//////+73ardEe4REe7uzFWZZhFViKpmqszdRFV3qv d2/hsAAAAJcEhZcwAACxIAAAsSAdLdfvwAAAAVdEVYdENyZWF0aW9uIFRpbWUANi8yMC8wN 54b0bMAAAAgdEVYdFNvZnR3YXJlAE1hY3JvbWVkaWEgRmlyZXdvcmtzIE1Yu5EqJAAABHhJ REFUeJzt2WmTmzAMBmCXI9cSlhybc5P9//+yQBOQLBmwrDgznX2nHzpJUws9whBizG9+M5j bKfi/WAWtX5ahFWyuG/mHj0mdYxGw/OqapulZ2ISiTNqUN/H6m4+0iawJp6TLUbb86pw+41 9BcUxARAyba9rHl+FWJiiCWTynKB9eTTglJJ5NWFnrezb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