"Programming with Perl: Patch Up Those Image Tags"
by Randal Schwartz
Web Techniques, April 1999

Web Techniques grants permission to use these listings (and code) for 
private or commercial use provided that credit to Web Techniques and 
the author is maintained within the comments of the source. For 
questions, contact editors@web-techniques.com. 



NOTE: Remove line numbers!



[LISTING ONE]


1  #!/usr/bin/perl -w
2  use strict;
3  
4  use URI::file;
5  
6  BEGIN {
7     package MyFilter;
8     use base qw(HTML::Filter);
9     use Image::Size;
10    use HTML::Entities;
11    use LWP::Simple;
12
13 sub new {
14    my $package = shift;
15    my $uri = shift;
16    my $self = $package->SUPER::new(@_);
17    $self->{_uri} = $uri;
18    $self;
19  }
20
21 sub start {
22    my $self = shift;
23    my($tag, $attr, $attrseq, $origtext) = @_;
24    if ($tag eq 'base' and exists $attr->{href}) {
25       $self->{_uri} = URI->new($attr->{href});
26    }
27    {
28      last unless $tag eq 'img';
29      last unless exists $attr->{src};
30      last if exists $attr->{width};
31      last if exists $attr->{height};
32      my $src = $attr->{src};
33      my $src_uri = URI->new_abs($src, $self->{_uri});
34      my @xy =
35        $src_uri->scheme eq "file" ?
36          imgsize($src_uri->path) :
37            imgsize(\get($src_uri));
38      last unless defined $xy[0];
39      @$attr{qw(width height)} = @xy[0,1];
40      my $tmp = "<$tag";
41      for (@$attrseq, qw(width height)) {
42        $tmp .= qq/ $_="/.encode_entities($attr->{$_}).q/"/;
43      }
44      $tmp .= ">";
45      $self->output($tmp);
46      return;
47    }
48    $self->output($origtext);
49  }
50 }
51
52   undef $/;
53   shift, $^I = ($1 || "~") if @ARGV and $ARGV[0] =~ /^-i(.*)/;
54   while (<>) {
55      my $file = URI::file->new_abs($ARGV);
56      print STDOUT "===== $ARGV =====\n";
57      MyFilter->new($file)->parse($_)->eof;
58   }