# (C) 2006 Brian Millham bmillham@hughes.net
# The perl artistic license applies.

use Win32::GUI;
use Win32::GUI::DIBitmap;
use Image::Magick;

use strict;
use warnings;

my $anifile = shift;
my $currentframe = 0;
my $image = Image::Magick->new();
# Replace with an animated gif of your choice
my $result = $image->Read($anifile);
# Get the number of frames
my $framecount = $#$image;
my $height = $image->[0]->Get('height');
my $width = $image->[0]->Get('width');
# An array to hold the individual images.
# The images are loaded in the timer.
my @frames;

# Get the frame delay.
# This assumes that all frames have the same delay
my $delay = $image->[0]->Get('delay');

# Get the first frame as a bitmap
push @frames, getFrameAsBmp(0);
print "Animation file: $anifile\n";
print "Height: $height\n";
print "Width: $width\n";
print "Framecount: $framecount\n";
print "Delay: $delay\n";

# Create the window, sized for the gif
my $W = new Win32::GUI::Window(
			       -title => "Animated GIF Test",
			       -pos => [100, 100],
			       -height => $height + 50,
			       -width => $width + 2,
			       -name => 'Window',
			      );

# Create the label to display the GIF
my $lbl = $W->AddLabel(
		       -top => 10,
		       -left => 1,
		       -height => $height,
		       -width => $width,
		       -bitmap => $frames[0],
		       -name => 'Animation',
		       -visible => 1,
		      );

# Add the timer to load and display the gif
# The delay is in 10ths of seconds.
$W->AddTimer('T1', $delay * 10);
# Show the main window.
$W->Show();

Win32::GUI::Dialog();

sub Window_Terminate {
  -1;
}

# Gets the frame, converts it to a bitmap and returns the bitmap
sub getFrameAsBmp {
  my $frameno = shift;
# Load the frame into memory
  my @frame = $image->[$frameno]->ImageToBlob();
# Create a DIBitmap object
  my $dib = newFromData Win32::GUI::DIBitmap($frame[0]);
# Convert it to a bitmap
  my $bmp = $dib->ConvertToBitmap();
  return $bmp;
}

sub T1_Timer {
  # Start over after the last frame
  $currentframe = 0 if $currentframe > $framecount;
  # If the frame has not been converted to a bitmap, get and convert it.
  push @frames, getFrameAsBmp($currentframe) if !defined $frames[$currentframe];
  # Display the frame
  $lbl->SetImage($frames[$currentframe++]);
}

  
