/[Frey]/trunk/lib/Frey/Web/CombineImages.pm
This is repository of my old source code which isn't updated any more. Go to git.rot13.org for current projects!
ViewVC logotype

Contents of /trunk/lib/Frey/Web/CombineImages.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1133 - (show annotations)
Tue Jun 30 15:10:55 2009 UTC (14 years, 10 months ago) by dpavlin
File size: 2054 byte(s)
make classes immutable and remove moose droppings to make Perl::Critic::Moose happy
1 package Frey::Web::CombineImages;
2 use Moose::Role;
3
4 with 'Frey::Path';
5 with 'Frey::Storage';
6
7 use Imager;
8 use Digest::MD5 qw/md5_hex/;
9 use File::Slurp;
10 use Data::Dump qw/dump/;
11
12 =head2 combine_images
13
14 Combine images into CSS sprites based on L<http://www.alistapart.com/articles/sprites/>
15
16 my ( $combined_path, $styles ) = $self->combine_images( @paths );
17
18 =cut
19
20 sub combine_images {
21 my $self = shift;
22 my @images = @_;
23
24 my $path = 'var/combine/' . md5_hex( join(' ',@images ) );
25 my $style_path = $path . '.yaml';
26 $path .= '.png';
27
28 return ( $path, $self->load( $style_path ) ) if -e $path;
29
30 warn "# path $path";
31 $self->mkbasepath( $path );
32
33 # fixed dimensions of images combined
34 my ( $w, $h ) = ( 16, 16 );
35 my $padding = 5; # space between pictures when used within text
36 my $num_images = $#images + 1;
37
38 return unless $num_images;
39
40 my $combined = Imager->new(
41 xsize => $w,
42 ysize => $num_images * ( $h + $padding ),
43 channels => 4, # RGB+alpha
44 ) || die "can't create $w x ",$num_images * ($h + $padding)," combined image";
45
46 my $y = 0;
47
48 my $style;
49
50 foreach my $image_path ( @images ) {
51 my $i = Imager->new;
52 $i->read( file => $image_path ) || die "can't open $image_path: $!";
53
54 die "with not $w" unless $i->getwidth == $w;
55 die "with not $h" unless $i->getheight == $h;
56
57 warn "# copy $image_path 0 x $y" if $self->debug;
58 $combined->paste( img => $i, left => 0, top => $y );
59
60 $style->{$image_path}
61 = qq|<span style="|
62 . qq|background: url(/$path) no-repeat 0px | . -$y . qq|px; |
63 . qq|padding: 0 0 0 | . ( $w + 3 ) . qq|px; |
64 . qq|width: ${w}px; height: ${h}px; |
65 . qq|"> </span>|;
66 ;
67
68 $y += $h + $padding;
69 }
70
71 $combined->write( file => $path ) || die "can't write $path: $!";
72 $self->store( $style_path, $style ) || die "can't store $style_path: $!";
73 warn
74 "# combined $num_images ${w}x${h} images into ",
75 $combined->getwidth, "x", $combined->getheight, " ",
76 $path, " ", -s $path , " bytes ",
77 " style $style_path ", -s $style_path, " bytes";
78
79 return ( $path, $style );
80 }
81
82 no Moose::Role;
83
84 1;

  ViewVC Help
Powered by ViewVC 1.1.26