短的Base64编码程序:
# to_base64.pl
use MIME::Base64 qw(encode_base64);
open (IMAGE, $ARGV[0]) || die "$!";
binmode(IMAGE);
local $/;
my $file_contents = <IMAGE>;
close IMAGE;
open (B64, ">$ARGV[0].b64") || die $!;
print B64 encode_base64($file_contents);
close B64;
print "output file is $ARGV[0].b64\n";
与此命令行使用它:
perl to_base64.pl image_file.jpg
它写入一个含有Base64编码输入的文件名为image_file.jpg.b64
文件。
要解码的Base64,你可以使用这个脚本:
# decode_base64.pl
use MIME::Base64 qw(decode_base64);
open (B64, $ARGV[0]) || die "$!";
local $/;
my $base64_string = <B64>;
close B64;
my $filename;
if ($ARGV[0] =~ /.\.b64$/i) {
$filename = substr($ARGV[0], 0, length($ARGV[0]) - 4);
}
else {
$filename = "$ARGV[0].bin";
}
open (IMAGE, ">$filename") || die $!;
binmode(IMAGE);
print IMAGE decode_base64($base64_string);
close IMAGE;
print "output file is $filename\n";
使用此命令行调用它:
perl decode_base64.pl my_base64_file.b64
如果作为参数提供给该脚本文件名以.b64
结束这些尾随4字符将被删除:image_file.jpg.b64
=>image_file.jpg
。否则,该脚本会将.bin
添加到输入文件名以获取输出文件名。
反斜杠在双引号内有特殊含义。你可以使用单引号('C:\ wamp \ www \ image.png''),用更多的反斜杠('“C:\\ wamp \\ www \\ image.png”')转义反斜杠,或者只是使用正斜杠(确实如此):'“C:/wamp/www/image.png”'。 – mob
Windows上的Mime :: Base64模块似乎有问题(至少在ActiveState perl 5.8.8中) - 是的,我试图用'使用Mime :: Base64 qw(decode_base64)'导入该子例程。 –