Perl GD 模块 PNG 图像损坏或无法打开

Perl GD module PNG image corrupt or cant open

我 运行ning Windows 10 岁,我已经安装了 Perl v5.26.1,专为 MSWin32-x64-多线程构建。 ActiveState 提供的二进制版本 2601 [404865]。

我的问题是我想使用 GD::Graph。

一切看起来都很好。我写了一段代码并做了语法检查,一切都很好。当我 运行 脚本时,我得到的只是废话。我尝试输出到 *.png 文件,但文件已损坏。

这快把我逼疯了。我在这里做错了什么?任何帮助将非常感激。以下是代码

#!usr/bin/perl -w
use strict;
use GD::Graph::area;
# File: prob1.pl

my @x = (0, 0, 0.00759, 0.018975, 0.036053, 0.216319, 0.449715, 0.648956, 
0.815939, 0.935484, 1);
my @y = (0, 0.053763, 0.16129, 0.308244, 0.577061, 0.792115, 0.874552, 
0.924731, 0.964158, 0.989247, 1);

my @data = (\@x, \@y);

my $graph = GD::Graph::area->new(500, 300);

$graph->set( x_label=>'False Positive Rate', y_label=>'True Positive 
Rate',title=>'ROC Curve') or warn $graph->error;

my $image = $graph->plot(\@data) or die $graph->error;

open IMG, ">prob1.png" or die "can't open prob1.png\n";
print IMG $image->png;
exit;

默认情况下,Perl 的 Windows 版本以 crlf 模式打开文件(用回车符 return + 新行替换输出流中的每个新行)。您不希望这种情况发生在您的 png 流上,因此您需要告诉 Perl 使用 raw 模式(输出原始字节)。

open IMG, ">:raw", "prob1.png";

是一种方法。

open IMG, ">", "prob1.png";
binmode IMG;

是另一个。 GD and GD::Graph 文档多次提请注意 binmode 的必要性。