Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: How to create and save an image from RGB values [Tk in ~0.059s]

by kcott (Archbishop)
on Dec 29, 2021 at 01:22 UTC ( #11139997=note: print w/replies, xml ) Need Help??


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

G'day bliako,

"Ideally, I would like a method which just takes in an array of RGB values and creates the image (fastly)."

The following Tk code does this.

#!/usr/bin/env perl use strict; use warnings; use Tk; use Tk::PNG; use Time::HiRes 'time'; my $mw = MainWindow::->new(); my @common_raw_rgbs; my $png_image = 'pm_11139959_image.png'; my ($W, $H) = (100, 100); { no warnings 'qw'; @common_raw_rgbs = qw{ #ff0000 #ffff00 #009900 #00ffff #0000ff #ff00ff }; } my @raw_rgbs = (@common_raw_rgbs) x int(1 + ($W * $H / (0+@common_raw_ +rgbs))); my $t0 = time; my $image = $mw->Photo(-format => 'png', -width => $W, -height => $H); my $i = 0; for my $y (0 .. $H - 1) { for my $x (0 .. $W - 1) { $image->put([$raw_rgbs[$i++]], -to => $x, $y, $x + 1, $y + 1); } } $image->write($png_image); my $t1 = time; $mw->Label(-text => 'Image:')->pack(); $mw->Label(-image => $image)->pack(); $mw->Label(-text => 'Time: ' . sprintf '%.6f', $t1 - $t0)->pack(); MainLoop;

Notes:

  • The GUI renders the image and shows the time taken.
    • The GUI image is exact size. I used Gimp to look at the disk copy and zoomed in to see details.
    • The time is measured from just before the unpopulated Tk::Photo is created, to just after the final PNG is written to disk — all tests gave this as a tad over 59ms; as always, YMMV.
  • I took some minor liberties with the array of RGB values — @raw_rgbs actually contains 10,002 elements; a 100x100 image only has 10,000 pixels — because I couldn't tell how you were aligning image size with array length.
    • If they're both the same size, nothing further needs doing.
    • If the array is smaller, you may want to pad the image with transparent pixels or, perhaps, use some default background colour.
    • If the array is larger you can: truncate the array; simply not use the excess elements (in my code, I didn't put() the last two elements); or, modify the image size at the outset (some decisions for you regarding how you'd want to go about this).

— Ken

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11139997]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (4)
As of 2022-08-18 23:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?