HTML中のイメージのwidthを調整するフィルタの作りかけ

widthが無い場合やスタイルで指定されている場合、外部cssの場合など
対応できないので今は使わないことにした。

なんかもっといい方法ないかなぁ

#!/usr/bin/perl

use strict;
use warnings;

use IO::File;
use HTML::Parser;
use Data::Dumper;

my $file = 'test.html';


my $fh = new IO::File;
$fh->open("< $file") or die "$!: $file";
my $str = join '', <$fh>;
$fh->close;

my $ret = img_resize($str);
print "$ret\n";

sub _img_resize {
    my ($self, $tag, $attr, $attrseq, $text) = @_;
    return unless $tag eq 'img' && $attr->{'width'};
    #print Dumper(\@_);
    $attr->{'width'} = int($attr->{'width'} * $self->{'ratio'});
    my $attr_text = join ' ', map { sprintf '%s="%s"', $_, $attr->{$_} } grep !/height/, @$attrseq;
    $self->{'ret'} .= "<$tag $attr_text>\n";
};
sub img_resize {
    my $str = shift;
    my $p = HTML::Parser->new;
    $p->{'ratio'} = shift || '0.5';
    $p->handler( start => \&_img_resize );
    $p->handler( declaration  => sub { return; $_[0]->{'ret'} .= "<!$_[1]>"     } );
    $p->handler( process      => sub { return; $_[0]->{'ret'} .= $_[2]          } );
    $p->handler( comment      => sub { return; $_[0]->{'ret'} .= "<!--$_[1]-->" } );
    $p->handler( end          => sub { return; $_[0]->{'ret'} .= $_[2]          } );
    $p->handler( text         => sub { return; $_[0]->{'ret'} .= $_[1]          } );
    $p->parse($str);
    return $p->{'ret'};
};