http://www.perlmonks.org?node_id=11139982


in reply to How to create and save an image from RGB values

This works for me. I have used Image::PNG::Libpng. Somehow last night, in the dark, it looked scary but in the light of day it turns out to be quite adorable. And fast too.

use Image::PNG::Libpng ':all'; use Image::PNG::Const ':all'; my $W = 500; my $H = 500; my $compression_level = 9; ################################# my %ihdr = ( width => $W, height => $H, bit_depth => 8, # one of: PNG_COLOR_TYPE_GRAY, PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLO +R_TYPE_PALETTE, PNG_COLOR_TYPE_RGB, PNG_COLOR_TYPE_RGB_ALPHA. color_type => PNG_COLOR_TYPE_RGB, ); my @rows; for my $y (0..$H-1){ # each row is a binary string packing $W (R,G,B) triplets (not + an array) # so we keep appending to this binary buffer (a string! but bi +nary string ok,right?) my $col_bin_str = ""; for my $x (0..$W-1){ my $R = int(rand()*0x100); my $G = int(rand()*0x100); my $B = int(rand()*0x100); # test compression with this "compressable" content # my ($R, $G, $B) = (0xFF) x 3; # pack an R,G,B tripplet into 3 bytes, each an unsingned char # that would be different for different scheme (RGBA) +etc. $col_bin_str .= pack "CCC", $R, $G, $B; } push @rows, $col_bin_str; } my $png = create_writer('file.png'); $png->set_compression_level($compression_level); $png->set_IHDR(\%ihdr); $png->set_rows(\@rows); $png->write_png();

bw, bliako