为什么我的图像在被这个Perl CGI脚本提供时会被剪裁?

Jer*_*Gwa 2 perl jpeg cgi

当我尝试STDOUT在Perl CGI脚本中打印图像时,在浏览器中查看时图像会被剪裁.

这是以下代码:

if ($path =~ m/\.jpe?g$/i)
{    
  my $length = (stat($path))[7];
  $| = 1;
  print "Content-type: image/jpg\r\n";
  print "Content-length: $length\r\n\r\n";
  open(IMAGE,"<$path");
  binmode(IMAGE);
  binmode(STDOUT);
  my ($image, $buff);
  read IMAGE, $buff, $length;
  syswrite STDOUT, $buff, $length;
  close IMAGE;
}
Run Code Online (Sandbox Code Playgroud)

Sin*_*nür 5

如果你真的想在服务之前将整个文件读入内存,请使用File :: Slurp:

#!/usr/bin/perl

use strict; use warnings;

use CGI::Simple;
use File::Slurp;
use File::stat;

local $| = 1;

my $cgi = CGI::Simple->new;

my $st = stat($path) or die "Cannot stat '$path'";

print $cgi->header(
    -type => 'image/jpeg',
    -length => $st->size,
);

write_file(\*STDOUT, {binmode => ':raw'}, 
    \ read_file( $path, binmode => ':raw' )
);
Run Code Online (Sandbox Code Playgroud)

但是,读取整个文件会占用大量图像的大量内存.因此,请参阅如何使用Perl CGI脚本提供图像?.