slicks1 slicks1 - 9 months ago 29
Perl Question

Copy image contents (not copying two files)

I'm new to perl. Here is my current code:

my $path = '/pathtoimage/image.jpg'
my $jpg=GD::Image->newFromJpeg($path,1);
my ($nw,$nh,$x,$y)=(80,80,0,0);
my ($ar,$nr)=($w/$h,$nw/$nh);
my ($ow,$oh)=($nw,$nh);
if ($ar>$nr) {
} elsif ($ar<$nr) {
my $string2;
$string2 .= $chars[rand @chars] for 1..8;
$string2 = '/path/'.$string2.'.jpg';
my $thumb=GD::Image->new($ow,$oh,1);

I'd like to get the contents of
into a new,uncreated jpeg file.

How do I do this?


All the information is in the documentation of the GD module:

 # make sure we are writing to a binary stream
binmode STDOUT;

# Convert the image to PNG and print it on standard output
print $im->png;

Instead of having the output in STDOUT you want it in a file, and also instead of a .png format you prefer a .jpeg. Having a look at the output methods of the GD library there is one for JPEG data: $jpegdata = $image->jpeg([$quality]).

$jpegdata = $image->jpeg([$quality])

This returns the image data in JPEG format. You can then print it, pipe it to a display program, or write it to a file. You may pass an optional quality score to jpeg() in order to control the JPEG quality. This should be an integer between 0 and 100. Higher quality scores give larger files and better image quality. If you don't specify the quality, jpeg() will choose a good default.

The code you want should be something like:

open my $fd, '>', '<path_to_your_new_jpeg>';
binmode $fd;
print $fd $thumb->jpeg(100); # 100 for 100% quality
close $fd;