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, scan => 1);
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 push @{$links{$params{page}}}, $image;
35 my $file = bestlink($params{page}, $image);
37 my $dir = $params{page};
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 ".sprintf(gettext('bad size "%s"'), $size)."]]"
49 unless (defined $w && defined $h);
51 my $outfile = "$config{destdir}/$dir/${w}x${h}-$base";
52 $imglink = "$dir/${w}x${h}-$base";
54 will_render($params{page}, $imglink);
56 if (-e $outfile && (-M srcfile($file) >= -M $outfile)) {
57 $r = $im->Read($outfile);
58 return "[[img ".sprintf(gettext("failed to read %s: %s"), $outfile, $r)."]]" if $r;
61 $r = $im->Read(srcfile($file));
62 return "[[img ".sprintf(gettext("failed to read %s: %s"), $file, $r)."]]" if $r;
64 $r = $im->Resize(geometry => "${w}x${h}");
65 return "[[img ".sprinftf(gettext("failed to resize: %s"), $r)."]]" if $r;
67 # don't actually write file in preview mode
68 if (! $params{preview}) {
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=urlto($file, $params{destpage});
88 $imgurl=urlto($imglink, $params{destpage});
91 $fileurl="$config{url}/$file";
92 $imgurl="$config{url}/$imglink";
95 if (! defined($im->Get("width")) || ! defined($im->Get("height"))) {
96 return "[[img ".sprintf(gettext("failed to determine size of image %s"), $file)."]]";
99 return '<a href="'.$fileurl.'"><img src="'.$imgurl.
100 '" alt="'.$alt.'" width="'.$im->Get("width").
101 '" height="'.$im->Get("height").'"'.
102 (exists $params{class} ? ' class="'.$params{class}.'"' : '').
103 (exists $params{id} ? ' id="'.$params{id}.'"' : '').