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)
36 || return "[[img ".sprintf(gettext("%s not found"), $image)."]]";
38 my $dir = IkiWiki::dirname($file);
39 my $base = IkiWiki::basename($file);
41 eval q{use Image::Magick};
43 my $im = Image::Magick->new;
47 if ($size ne 'full') {
48 my ($w, $h) = ($size =~ /^(\d+)x(\d+)$/);
49 return "[[img ".sprintf(gettext('bad size "%s"'), $size)."]]"
50 unless (defined $w && defined $h);
52 my $outfile = "$config{destdir}/$dir/${w}x${h}-$base";
53 $imglink = "$dir/${w}x${h}-$base";
55 if (-e $outfile && (-M srcfile($file) >= -M $outfile)) {
56 $r = $im->Read($outfile);
57 return "[[img ".sprintf(gettext("failed to read %s: %s"), $outfile, $r)."]]" if $r;
60 $r = $im->Read(srcfile($file));
61 return "[[img ".sprintf(gettext("failed to read %s: %s"), $file, $r)."]]" if $r;
63 $r = $im->Resize(geometry => "${w}x${h}");
64 return "[[img ".sprinftf(gettext("failed to resize: %s"), $r)."]]" if $r;
66 # don't actually write file in preview mode
67 if (! $params{preview}) {
68 will_render($params{page}, $imglink);
69 my @blob = $im->ImageToBlob();
70 writefile($imglink, $config{destdir}, $blob[0], 1);
78 $r = $im->Read(srcfile($file));
79 return "[[img ".sprintf(gettext("failed to read %s: %s"), $file, $r)."]]" if $r;
83 add_depends($imglink, $params{page});
85 my ($fileurl, $imgurl);
86 if (! $params{preview}) {
87 $fileurl=IkiWiki::abs2rel($file, IkiWiki::dirname($params{destpage}));
88 $imgurl=IkiWiki::abs2rel($imglink, IkiWiki::dirname($params{destpage}));
91 $fileurl="$config{url}/$file";
92 $imgurl="$config{url}/$imglink";
95 return '<a href="'.$fileurl.'"><img src="'.$imgurl.
96 '" alt="'.$alt.'" width="'.$im->Get("width").
97 '" height="'.$im->Get("height").'" /></a>';