Search code examples
perlpngbioperl

Why is this script creating a corrupted PNG file on Windows?


I am trying to create a PNG file.

The script below executes without returning any errors, the output file tester.png cannot be viewed (and the cmd window prints the attached the attached text).

I am not sure why I cannot view the PNG file produced by this script.

I have used both Active Perl (5.18.2) and also Strawberry Perl (5.18.4.1) but same problem. I tried Strawberry Perl as it has libgd and libpng as part of the installation, even though I'm not getting any errors. Any advice?

#!/usr/bin/perl

use Bio::Graphics;
use Bio::SeqFeature::Generic;
use strict;
use warnings;

my $infile = "data1.txt";
open( ALIGN, "$infile" ) or die;
my $outputfile = "tester.png";
open( OUTFILE, ">$outputfile" ) or die;

my $panel = Bio::Graphics::Panel->new(
    -length => 1000,
    -width  => 800
);
my $track = $panel->add_track(
    -glyph => 'generic',
    -label => 1
);

while (<ALIGN>) {    # read blast file
    chomp;

    #next if /^\#/;  # ignore comments
    my ( $name, $score, $start, $end ) = split /\t+/;
    my $feature = Bio::SeqFeature::Generic->new(
        -display_name => $name,
        -score        => $score,
        -start        => $start,
        -end          => $end
    );
    $track->add_feature($feature);

}

binmode STDOUT;
print $panel->png;
print OUTFILE $panel->png;

screenshot of cmd print


Solution

  • You have

    binmode STDOUT;
    print $panel->png;
    

    Interestingly, you also have:

    print OUTFILE $panel->png;
    

    but you never binmode OUTFILE. So, you display the contents of the PNG file in the command prompt, and create a corrupt PNG file. (see also When bits don't stick.)

    If you remove the print OUTFILE ..., and redirect the output of your script to a PNG file, you should be able to view its contents in an image viewer.

    C:\> perl myscript.pl > panel.png

    Alternatively, you can avoid printing the contents of a binary file to the console window, and instead use

    binmode OUTFILE;
    print $panel->png;