Skip to content

Instantly share code, notes, and snippets.

@silvers
Created August 31, 2012 04:04
Show Gist options
  • Save silvers/3548960 to your computer and use it in GitHub Desktop.
Save silvers/3548960 to your computer and use it in GitHub Desktop.
Generating image and css for CSS Sprite.
use strict;
use warnings;
use File::Basename;
use File::Find::Rule;
use Getopt::Long;
use Image::Imlib2;
sub main {
Getopt::Long::GetOptions(
'--dir=s' => \my $target_dir,
'--filenames=s{,}' => \my @target_filenames,
'--prefix=s' => \my $prefix,
);
unless( $target_dir ) {
die "Usage $0 --dir='target_dir'";
}
# calculate sprite_image size
my $blend_images = {};
my ($sprite_image_width, $sprite_image_height) = (0, 0);
my $rule = File::Find::Rule->new;
$rule->file;
$rule->name( @target_filenames ) if @target_filenames;
my @files = $rule->in($target_dir);
for my $file (@files){
my ($filename, ) = fileparse($file, qw(.png .gif .jpg));
my $image = Image::Imlib2->load($file);
$blend_images->{$filename} = $image;
$sprite_image_width = $image->width if $image->width > $sprite_image_width;
$sprite_image_height += $image->height + 1; # add 1px space
}
# create sprite image
my $img_sprite = Image::Imlib2->new_transparent($sprite_image_width, $sprite_image_height);
my @css;
my ($x, $y) = (0, 0);
for my $filename ( sort keys %{ $blend_images} ) {
my $image = $blend_images->{$filename};
$img_sprite->blend(
$image, 1,
0, 0, $image->width, $image->height,
$x, $y, $image->width, $image->height,
);
my $selecter = $prefix ? "$prefix-$filename" : $filename;
my $css = ".$selecter { background-position: -${x}px -${y}px; width: @{[$image->width]}px; height: @{[$image->height]}px; }";
push @css, $css;
$y += $image->height + 1; # space
}
$img_sprite->save('sprite.png');
# create sprite css
my css_filename = 'sprite.css'; #TODO: get option
open my $fh, '>', $css_filename or die $!;
for my $line ( @css ) {
$line =~ s/-0px/0/g;
print $fh "$line\n";
}
close $fh;
}
main();
__END__
=pod
=head1 NAME
sprite_maker.pl - Generating image and css for CSS Sprite.
=head1 SYNOPSIS
sprite_maker.pl [ options... ]
=head1 OPTIONS
=over 3
=item -d.--dir (required)
--dir path/to/imagedir
=item -f,--filenames
--filenames hoge.png huga.png ..
--filenames `cd path/to/imagedir && ls *.png`
=item -p,--prefix
Insert before the class name.
ex. --prefix sprite
=back
=head1 AUTHOR
silvers
=cut
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment