image2ascii.pl 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #!/usr/bin/perl
  2. # Author: Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Date: 27 August 2015
  5. # Website: https://github.com/trizen
  6. # Generate an ASCII representation for an image
  7. use 5.010;
  8. use strict;
  9. use autodie;
  10. use warnings;
  11. use GD qw();
  12. use Getopt::Long qw(GetOptions);
  13. GD::Image->trueColor(1);
  14. my $size = 80;
  15. sub help {
  16. my ($code) = @_;
  17. print <<"HELP";
  18. usage: $0 [options] [files]
  19. options:
  20. -w --width=i : width size of the ASCII image (default: $size)
  21. example:
  22. perl $0 --width 200 image.png
  23. HELP
  24. exit($code);
  25. }
  26. GetOptions('w|width=s' => \$size,
  27. 'h|help' => sub { help(0) },)
  28. or die "Error in command-line arguments!";
  29. sub avg {
  30. ($_[0] + $_[1] + $_[2]) / 3;
  31. }
  32. sub img2ascii {
  33. my ($image) = @_;
  34. my $img = GD::Image->new($image) // return;
  35. my ($width, $height) = $img->getBounds;
  36. if ($size != 0) {
  37. my $scale_width = $size;
  38. my $scale_height = int($height / ($width / ($size / 2)));
  39. my $resized = GD::Image->new($scale_width, $scale_height);
  40. $resized->copyResampled($img, 0, 0, 0, 0, $scale_width, $scale_height, $width, $height);
  41. ($width, $height) = ($scale_width, $scale_height);
  42. $img = $resized;
  43. }
  44. my $avg = 0;
  45. my @averages;
  46. foreach my $y (0 .. $height - 1) {
  47. foreach my $x (0 .. $width - 1) {
  48. my $index = $img->getPixel($x, $y);
  49. push @averages, avg($img->rgb($index));
  50. $avg += $averages[-1] / $width / $height;
  51. }
  52. }
  53. unpack("(A$width)*", join('', map { $_ < $avg ? 1 : 0 } @averages));
  54. }
  55. say for img2ascii($ARGV[0] // help(1));