summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/img.pm
blob: 120326910988e4a2457b16268a89a79b7349e7e5 (plain)
  1. #!/usr/bin/perl
  2. # Ikiwiki enhanced image handling plugin
  3. # Christian Mock cm@tahina.priv.at 20061002
  4. package IkiWiki::Plugin::img;
  5. use warnings;
  6. use strict;
  7. use IkiWiki;
  8. use Image::Magick;
  9. my %imgdefaults;
  10. sub import { #{{{
  11. hook(type => "preprocess", id => "img", call => \&preprocess);
  12. } #}}}
  13. sub preprocess (@) { #{{{
  14. my ($image) = $_[0] =~ /$config{wiki_file_regexp}/; # untaint
  15. my %params=@_;
  16. if (! exists $imgdefaults{$params{page}}) {
  17. $imgdefaults{$params{page}} = {};
  18. }
  19. my $size = $params{size} || $imgdefaults{$params{page}}->{size} || 'full';
  20. my $alt = $params{alt} || $imgdefaults{$params{page}}->{alt} || '';
  21. if ($image eq 'defaults') {
  22. $imgdefaults{$params{page}} = {
  23. size => $size,
  24. alt => $alt,
  25. };
  26. return '';
  27. }
  28. add_depends($params{page}, $image);
  29. my $file = bestlink($params{page}, $image) || return "[[img $image not found]]";
  30. my $dir = IkiWiki::dirname($file);
  31. my $base = IkiWiki::basename($file);
  32. my $im = Image::Magick->new;
  33. my $imglink;
  34. my $r;
  35. if ($size ne 'full') {
  36. my ($w, $h) = ($size =~ /^(\d+)x(\d+)$/);
  37. return "[[img bad size \"$size\"]]" unless (defined $w && defined $h);
  38. my $outfile = "$config{destdir}/$dir/${w}x${h}-$base";
  39. $imglink = "$dir/${w}x${h}-$base";
  40. will_render($params{page}, $imglink);
  41. if (-e $outfile && (-M srcfile($file) >= -M $outfile)) {
  42. $r = $im->Read($outfile);
  43. return "[[img failed to read $outfile: $r]]" if $r;
  44. }
  45. else {
  46. $r = $im->Read(srcfile($file));
  47. return "[[img failed to read $file: $r]]" if $r;
  48. $r = $im->Resize(geometry => "${w}x${h}");
  49. return "[[img failed to resize: $r]]" if $r;
  50. my @blob = $im->ImageToBlob();
  51. writefile($imglink, $config{destdir}, $blob[0], 1);
  52. }
  53. }
  54. else {
  55. $r = $im->Read(srcfile($file));
  56. return "[[img failed to read $file: $r]]" if $r;
  57. $imglink = $file;
  58. }
  59. add_depends($imglink, $params{page});
  60. return '<a href="'.
  61. IkiWiki::abs2rel($file, IkiWiki::dirname($params{destpage})).
  62. '"><img src="'.
  63. IkiWiki::abs2rel($imglink, IkiWiki::dirname($params{destpage})).
  64. '" alt="'.$alt.'" width="'.$im->Get("width").
  65. '" height="'.$im->Get("height").'" /></a>';
  66. } #}}}
  67. 1;