#!/usr/bin/perl

use Gimp qw(:auto N_ __);
use Gimp::Fu;

podregister {
  my $out = $image->duplicate; # only work on duplicate
  my @layers = gimp_image_get_layers($out);
  die __"You need at least 2 layers to perform prep4gif\n" if @layers < 2;

# Show the image early - this makes debugging a breeze
  my $newdisplay = Gimp::Display->new($out);
# Hide the bottom layer, so it doesn't get into the merge visible later.
  my $bottomlayer = $layers[$#layers];
  gimp_item_set_visible($bottomlayer, 0);
  gimp_layer_add_alpha($bottomlayer);
  my $foreground;
  if ($#layers > 1) {
    $foreground = gimp_image_merge_visible_layers($out, 0);
  } else {
    $foreground = $layers[0];
  }

  my $layer_mask = gimp_layer_create_mask($foreground,2);
  gimp_layer_add_mask ($foreground, $layer_mask);
  gimp_threshold($layer_mask,$threshold,255);

# Transfer layer mask to selection, and grow the selection
  gimp_image_select_item($out, CHANNEL_OP_REPLACE, $foreground);
  gimp_selection_grow($out,$growth);

# Apply this selection to the background
  gimp_item_set_visible($bottomlayer, 1);
  gimp_image_set_active_layer($out, $bottomlayer);
  gimp_selection_invert($out);
  gimp_edit_cut($bottomlayer);

# Clean up after yourself
  gimp_layer_remove_mask($foreground, 1);
  my $outlayer = gimp_image_merge_visible_layers($out,0);

# Convert to indexed
  gimp_image_convert_indexed($out,1, MAKE_PALETTE, $colors, $dither, 1, "")
    if $index;
  ();
};

exit main;
__END__

=head1 NAME

prep4gif - Prep for gif

=head1 SYNOPSIS

<Image>/Filters/Web/Prepare for GIF...

=head1 DESCRIPTION

Make the image a small-cut-out of the intended background, so your
transparent text doesn't look blocky.

=head1 PARAMETERS

 [PF_INT32, "threshold", "Lower alpha threshold", 64],
 [PF_INT32, "growth", "How much growth for safety ",1],
 [PF_TOGGLE, "index", "Convert image to indexed", 0],
 [PF_TOGGLE, "dither", "Floyd-Steinberg dithering", 1],
 [PF_INT32, "colors", "Colors to quantize to", "255"],

=head1 IMAGE TYPES

RGB*

=head1 HISTORY

 prep4gif.pl
 by Seth Burgess <sjburges@gimp.org>
 June 29, 1998

 This perl plug-in prepares a multilayer RGB image for use as a
 transparent gif.  To use this prpoerly, you want to have something
 close to the intended background as the bottom layer.  If convert
 to indexed is not selected, the bottom two options are unused.

 12/5/03: <sjburges@gimp.org>
  s/gimp_convert/gimp_image_convert

 2/25/04: <sjburges@gimp.org>
  s/gimp_layer_set_visible/gimp_drawable_set_visible/

=head1 AUTHOR

Seth Burgess <sjburges@gimp.org>

=head1 DATE

2-15-98

=head1 LICENSE

Distributed under the same terms as Gimp-Perl.
