Perl 小品集 ─ imagesize

#!/usr/bin/perl
# imagesize.pl
#
# HTML ファイルに画像のサイズを入れる
# wkf, ImageMagic が必要

# ファイル名が入力されたかどうか
$input = $ARGV[0];
if ($input eq ""){
    print "This will put image size into a HTML file.\n";
    print "Input filename.\n";
    exit (0);
    }

# ファイルの漢字コードを euc にする
system ("wkf -e $input > $input.bak");

# ファイルを開く
open INP, "$input.bak" or die $!;
open OUT, "> $input" or die $!;

# ファイルから1行づつ読み取る
foreach $line (<INP>){
    chomp $line;
    # 漢字コードの読み取り
    if ($line =~ /charset=([\S]+)">$/){
        $k_code = $1;
        }
    # 画像ファイル名の読み取り
    # すでに画像サイズがある場合はスキップ
    if ($line =~ /<img src="([\S]+)" /i and $line !~ /width=/i){
        $imgfile = $1;
        # サブルーチンで処理
        $replace = &get_size($imgfile);
        # 画像サイズの書き込み
        $line =~ s/<img src="$imgfile" /$replace/;
        print OUT "$line\n";
        }
    else{
        print OUT "$line\n";
        }
    }
close (OUT);

# もとのファイルが sjis コードの場合の処理
if ($k_code eq "Shift_JIS"){
    system ("mv $input $input.euc");
    system ("wkf -Ds $input.euc > $input");
    unlink ("$input.euc");
    }
exit (0);

sub get_size(){
# ローカル変数の宣言
local ($imgfile, $line, @data, @size, $width, $height, $replace);
# 引数の取得
($imgfile) = @_;
# ImageMagic を使って画像データを得る
open IMAG, "identify $imgfile |" or die $!;
$line = <IMAG>;
chomp $line;
# 画像データから横サイズ、縦サイズを得る
@data = split / /, $line;
@size = split /x/, $data[1];
$width = $size[0];
$height = $size[1];
# 書き換える文字列を用意
$replace = "<img src=\"$imgfile\" width=\"$width\" height=\"$height\" ";
# 確認のため、画面にも出力
print "$replace\n";
return $replace;
}


[INDEX]