color_wheel.pl 848 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. #!/usr/bin/perl
  2. # Draw a HSV color wheel.
  3. # Algorithm from:
  4. # https://rosettacode.org/wiki/Color_wheel
  5. use 5.010;
  6. use strict;
  7. use warnings;
  8. use Imager;
  9. use Math::GComplex qw(cplx i);
  10. my ($width, $height) = (300, 300);
  11. my $center = cplx($width / 2, $height / 2);
  12. my $img = Imager->new(xsize => $width,
  13. ysize => $height);
  14. my $pi = atan2(0, -1);
  15. foreach my $y (0 .. $height - 1) {
  16. foreach my $x (0 .. $width - 1) {
  17. my $vector = $center - $x - $y * i;
  18. my $magnitude = 2 * abs($vector) / $width;
  19. my $direction = ($pi + atan2($vector->real, $vector->imag)) / (2 * $pi);
  20. $img->setpixel(
  21. x => $x,
  22. y => $y,
  23. color => {hsv => [360 * $direction, $magnitude, $magnitude < 1 ? 1 : 0]}
  24. );
  25. }
  26. }
  27. $img->write(file => 'color_wheel.png');