I'm trying to change some pixel's color in a PNG file. As a test, the following script should read a (256x256) PNG file, draw a red diagonal on it, and write the resulting image to file. There's a diagonal alright, but it's white. What am I missing?
#!/usr/bin/env perl
use GD;
$in_file = "in_file.png";
open($PNG,"<$in_file");
$im = newFromPng GD::Image($PNG) or die "Cannot open $in_file for importing";
close($PNG);
$red = $im->colorAllocate(255,0,0);
for($i=0;$i<256;$i++) {
$im->setPixel($i,$i,$red);
}
$out_file = "out_file.png";
open($IF,">$out_file") or die "Cannot open $out_file for writing?";
binmode $IF;
print $IF $im->png();
close($IF);
Answers
It looks like you're missing the step to create a new GD::Image object with the same dimensions as the input image before drawing the diagonal. Here's the modified script:
#!/usr/bin/env perl
use GD;
$in_file = "in_file.png";
open(my $PNG, "<", $in_file) or die "Cannot open $in_file for importing: $!";
my $im = GD::Image->newFromPng($PNG) or die "Cannot create image from $in_file";
close($PNG);
# Create a new image with the same dimensions as the input image
my $out_im = GD::Image->new($im->width, $im->height);
# Copy the input image to the output image
$out_im->copy($im, 0, 0, 0, 0, $im->width, $im->height);
$red = $out_im->colorAllocate(255, 0, 0);
# Draw the diagonal on the output image
for (my $i = 0; $i < $im->width; $i++) {
$out_im->setPixel($i, $i, $red);
}
$out_file = "out_file.png";
open(my $OF, ">", $out_file) or die "Cannot open $out_file for writing: $!";
binmode $OF;
print $OF $out_im->png();
close($OF);
In this modified version, I've added the creation of a new GD::Image object called $out_im
with the same dimensions as the input image $im
. Then, I copied the input image to the output image using the copy
method. Finally, I drew the red diagonal on the output image $out_im
instead of the input image $im
. This should result in the red diagonal being drawn on the image written to the output file.