2 # Ikiwiki enhanced image handling plugin
3 # Christian Mock cm@tahina.priv.at 20061002
4 package IkiWiki::Plugin::img;
13 hook(type => "preprocess", id => "img", call => \&preprocess);
16 sub preprocess (@) { #{{{
17 my ($image) = $_[0] =~ /$config{wiki_file_regexp}/; # untaint
20 if (! exists $imgdefaults{$params{page}}) {
21 $imgdefaults{$params{page}} = {};
23 my $size = $params{size} || $imgdefaults{$params{page}}->{size} || 'full';
24 my $alt = $params{alt} || $imgdefaults{$params{page}}->{alt} || '';
26 if ($image eq 'defaults') {
27 $imgdefaults{$params{page}} = {
34 add_depends($params{page}, $image);
35 my $file = bestlink($params{page}, $image) || return "[[img $image not found]]";
37 my $dir = IkiWiki::dirname($file);
38 my $base = IkiWiki::basename($file);
40 eval q{use Image::Magick};
42 my $im = Image::Magick->new;
46 if ($size ne 'full') {
47 my ($w, $h) = ($size =~ /^(\d+)x(\d+)$/);
48 return "[[img bad size \"$size\"]]" unless (defined $w && defined $h);
50 my $outfile = "$config{destdir}/$dir/${w}x${h}-$base";
51 $imglink = "$dir/${w}x${h}-$base";
53 if (-e $outfile && (-M srcfile($file) >= -M $outfile)) {
54 $r = $im->Read($outfile);
55 return "[[img failed to read $outfile: $r]]" if $r;
58 $r = $im->Read(srcfile($file));
59 return "[[img failed to read $file: $r]]" if $r;
61 $r = $im->Resize(geometry => "${w}x${h}");
62 return "[[img failed to resize: $r]]" if $r;
64 # don't actually write file in preview mode
65 if (! $params{preview}) {
66 will_render($params{page}, $imglink);
67 my @blob = $im->ImageToBlob();
68 writefile($imglink, $config{destdir}, $blob[0], 1);
76 $r = $im->Read(srcfile($file));
77 return "[[img failed to read $file: $r]]" if $r;
81 add_depends($imglink, $params{page});
83 my ($fileurl, $imgurl);
84 if (! $params{preview}) {
85 $fileurl=IkiWiki::abs2rel($file, IkiWiki::dirname($params{destpage}));
86 $imgurl=IkiWiki::abs2rel($imglink, IkiWiki::dirname($params{destpage}));
89 $fileurl="$config{url}/$file";
90 $imgurl="$config{url}/$imglink";
93 return '<a href="'.$fileurl.'"><img src="'.$imgurl.
94 '" alt="'.$alt.'" width="'.$im->Get("width").
95 '" height="'.$im->Get("height").'" /></a>';