Skip to content

Instantly share code, notes, and snippets.

@JaHIY
Last active August 29, 2015 14:05
Show Gist options
  • Save JaHIY/2d0ff29fd28b39282e3a to your computer and use it in GitHub Desktop.
Save JaHIY/2d0ff29fd28b39282e3a to your computer and use it in GitHub Desktop.
generate mosaic picture
#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
use autodie;
use 5.010;
use Data::Dumper;
use Image::Magick;
use Readonly;
Readonly my @COLORS => ('#FFFB0B',
'#179CDF',
'#F6276F',
'#12B936',
'#FFFFFF',
'#ABDE1D',
);
sub get_random_element_from {
my ( $array ) = @_;
return $array->[ rand @{$array} ];
}
my %monomer = ( amount => 8,
height => 64,
width => 64,
);
my %polymer = ( height => $monomer{'amount'} * $monomer{'height'},
width => $monomer{'amount'} * $monomer{'width'},
);
my $image = Image::Magick->new(size => sprintf('%sx%s', $polymer{'height'}, $polymer{'width'}));
$image->ReadImage('canvas:transparent');
my $grid = [];
for (my $y = 0; $y < $monomer{'amount'}; $y++) {
for (my $x = 0; $x < $monomer{'amount'}; $x++) {
my @colors = ();
if ( $x > 0 ) {
push @colors, $grid->[$x-1][$y];
}
if ( $y > 0 ) {
push @colors, $grid->[$x][$y-1];
=comment
if ( $x > 0 ) {
push @colors, $grid->[$x-1][$y-1];
}
if ( $x < $monomer{'amount'} - 1 ) {
push @colors, $grid->[$x+1][$y-1];
}
=cut
}
my @different_colors = grep { not $_ ~~ @colors } @COLORS;
my $color = get_random_element_from(\@different_colors);
$grid->[$x][$y] = $color;
$image->Draw(fill => $color,
primitive => 'rectangle',
points => sprintf('%s,%s %s,%s',
$x*$monomer{'height'},
$y*$monomer{'width'},
($x+1)*$monomer{'height'},
($y+1)*$monomer{'width'}),
);
}
}
print Dumper($grid);
$image->Write('a.png');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment