|
| 1 | +#!/usr/bin/perl |
| 2 | + |
| 3 | +# Author: Trizen |
| 4 | +# Date: 29 April 2025 |
| 5 | +# https://github.com/trizen |
| 6 | + |
| 7 | +# Extract the {R,G,B} channels of an image, as binary data. |
| 8 | + |
| 9 | +use 5.036; |
| 10 | +use GD qw(); |
| 11 | +use Getopt::Long qw(GetOptions); |
| 12 | + |
| 13 | +binmode(STDOUT, ':raw'); |
| 14 | + |
| 15 | +GD::Image->trueColor(1); |
| 16 | + |
| 17 | +my $size = 80; |
| 18 | +my $red = 0; |
| 19 | +my $green = 0; |
| 20 | +my $blue = 0; |
| 21 | + |
| 22 | +sub help($code = 0) { |
| 23 | + print <<"HELP"; |
| 24 | +usage: $0 [options] [files] |
| 25 | +
|
| 26 | +options: |
| 27 | + -w --width=i : resize image to this width (default: $size) |
| 28 | + -R --red : extract only the RED channel (default: $red) |
| 29 | + -G --green : extract only the GREEN channel (default: $green) |
| 30 | + -B --blue : extract only the BLUE channel (default: $blue) |
| 31 | +
|
| 32 | +example: |
| 33 | + perl $0 --width 200 --red image.png > red_channel.bin |
| 34 | +HELP |
| 35 | + exit($code); |
| 36 | +} |
| 37 | + |
| 38 | +GetOptions( |
| 39 | + 'w|width=s' => \$size, |
| 40 | + 'R|red!' => \$red, |
| 41 | + 'G|green!' => \$green, |
| 42 | + 'B|blue!' => \$blue, |
| 43 | + 'h|help' => sub { help(0) }, |
| 44 | + ) |
| 45 | + or die "Error in command-line arguments!"; |
| 46 | + |
| 47 | +sub img_unpack($image) { |
| 48 | + |
| 49 | + my $img = GD::Image->new($image) // return; |
| 50 | + my ($width, $height) = $img->getBounds; |
| 51 | + |
| 52 | + if ($size != 0) { |
| 53 | + my $scale_width = $size; |
| 54 | + my $scale_height = int($height / ($width / ($size / 2))); |
| 55 | + |
| 56 | + my $resized = GD::Image->new($scale_width, $scale_height); |
| 57 | + $resized->copyResampled($img, 0, 0, 0, 0, $scale_width, $scale_height, $width, $height); |
| 58 | + |
| 59 | + ($width, $height) = ($scale_width, $scale_height); |
| 60 | + $img = $resized; |
| 61 | + } |
| 62 | + |
| 63 | + my @values; |
| 64 | + |
| 65 | + foreach my $y (0 .. $height - 1) { |
| 66 | + foreach my $x (0 .. $width - 1) { |
| 67 | + my $index = $img->getPixel($x, $y); |
| 68 | + my ($R, $G, $B) = $img->rgb($index); |
| 69 | + |
| 70 | + if ($red) { |
| 71 | + push @values, $R; |
| 72 | + } |
| 73 | + if ($green) { |
| 74 | + push @values, $G; |
| 75 | + } |
| 76 | + if ($blue) { |
| 77 | + push @values, $B; |
| 78 | + } |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + my $output_width = $width * ($red + $green + $blue); |
| 83 | + return unpack("(A$output_width)*", pack('C*', @values)); |
| 84 | +} |
| 85 | + |
| 86 | +print for img_unpack($ARGV[0] // help(1)); |
0 commit comments