mtf_vertical_transform.pl 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/usr/bin/perl
  2. # Author: Trizen
  3. # Date: 06 April 2024
  4. # Edit: 09 April 2024
  5. # https://github.com/trizen
  6. # Scramble the pixels in each column inside an image, using the Move-to-front transform (MTF).
  7. use 5.036;
  8. use GD;
  9. use Getopt::Std qw(getopts);
  10. use Compression::Util qw(mtf_encode mtf_decode);
  11. GD::Image->trueColor(1);
  12. sub scramble_image ($file, $function) {
  13. my $image = GD::Image->new($file) || die "Can't open file <<$file>>: $!";
  14. my ($width, $height) = $image->getBounds();
  15. my $new_image = GD::Image->new($width, $height);
  16. my @alphabet = (0 .. 255);
  17. foreach my $x (0 .. $width - 1) {
  18. my @column;
  19. foreach my $y (0 .. $height - 1) {
  20. push @column, $image->rgb($image->getPixel($x, $y));
  21. }
  22. @column = @{$function->(\@column, \@alphabet)};
  23. foreach my $y (0 .. $height - 1) {
  24. $new_image->setPixel($x, $y, $new_image->colorAllocate(splice(@column, 0, 3)));
  25. }
  26. }
  27. return $new_image;
  28. }
  29. sub usage ($exit_code = 0) {
  30. print <<"EOT";
  31. usage: $0 [options] [input.png] [output.png]
  32. options:
  33. -d : decode the image
  34. -h : print this message and exit
  35. EOT
  36. exit($exit_code);
  37. }
  38. getopts('dh', \my %opts);
  39. my $input_file = $ARGV[0] // usage(2);
  40. my $output_file = $ARGV[1] // "output.png";
  41. if (not -f $input_file) {
  42. die "Input file <<$input_file>> does not exist!\n";
  43. }
  44. my $img = $opts{d} ? scramble_image($input_file, \&mtf_decode) : scramble_image($input_file, \&mtf_encode);
  45. open(my $out_fh, '>:raw', $output_file) or die "can't create output file <<$output_file>>: $!";
  46. print $out_fh $img->png(9);
  47. close $out_fh;