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