darken_image.pl 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #!/usr/bin/perl
  2. # Author: Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Date: 07 November 2015
  5. # Website: https://github.com/trizen
  6. # Replace the light-color pixels with their darken neighbors.
  7. # _________________
  8. # | | | |
  9. # | A | B | C |
  10. # |_____|_____|_____| _____
  11. # | | | | | |
  12. # | H | | D | --> | M |
  13. # |_____|_____|_____| |_____|
  14. # | | | |
  15. # | G | F | E |
  16. # |_____|_____|_____|
  17. # where M is the darkest color from (A, B, C, D, E, F, G, H)
  18. use 5.010;
  19. use strict;
  20. use warnings;
  21. use List::Util qw(min);
  22. use GD;
  23. GD::Image->trueColor(1);
  24. sub help {
  25. my ($exit_code) = @_;
  26. print <<"EOT";
  27. usage: $0 [input image] [output image]
  28. EOT
  29. exit($exit_code // 0);
  30. }
  31. my $in_file = shift(@ARGV) // help(2);
  32. my $out_file = shift(@ARGV) // 'output.png';
  33. my $img = GD::Image->new($in_file);
  34. my @matrix = ([]);
  35. my ($width, $height) = $img->getBounds;
  36. my $new_img = GD::Image->new($width, $height);
  37. sub get_pixel {
  38. $img->rgb($img->getPixel(@_));
  39. }
  40. foreach my $y (1 .. $height - 2) {
  41. foreach my $x (1 .. $width - 2) {
  42. my @left = get_pixel($x - 1, $y);
  43. my @right = get_pixel($x + 1, $y);
  44. my @down_left = get_pixel($x - 1, $y + 1);
  45. my @down_right = get_pixel($x + 1, $y + 1);
  46. my @up = get_pixel($x, $y - 1);
  47. my @down = get_pixel($x, $y + 1);
  48. my @up_left = get_pixel($x - 1, $y - 1);
  49. my @up_right = get_pixel($x + 1, $y - 1);
  50. $matrix[$y][$x] =
  51. $new_img->colorAllocate(
  52. min(($up[0], $down[0], $up_left[0], $up_right[0], $down_left[0], $down_right[0])),
  53. min(($up[1], $down[1], $up_left[1], $up_right[1], $down_left[1], $down_right[1])),
  54. min(($up[2], $down[2], $up_left[2], $up_right[2], $down_left[2], $down_right[2])),
  55. );
  56. }
  57. }
  58. for my $y (1 .. $height - 2) {
  59. for my $x (1 .. $width - 2) {
  60. $new_img->setPixel($x, $y, $matrix[$y][$x]);
  61. }
  62. }
  63. open(my $fh, '>:raw', $out_file) or die "Can't open `$out_file' for write: $!";
  64. print $fh (
  65. $out_file =~ /\.png\z/i ? $new_img->png
  66. : $out_file =~ /\.gif\z/i ? $new_img->gif
  67. : $new_img->jpeg
  68. );
  69. close $fh;