Click here to Skip to main content
Click here to Skip to main content

Adding GIF-animation using GDI+

, 29 Jan 2002
Rate this:
Please Sign up or sign in to vote.
Norm demonstrates how to coerce GDI+ into displaying animated GIFs

Motive

How many of you developers are using GDI+? I reckon, not many. As a seasoned Windows C++ programmer developing for desktop applications, I've been  using the archaic GDI on regular basis. Since the release of GDI+ (see (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/gdicpp) I've been using GDI+ in new applications and also converting existing applications to use GDI+. There numerous compelling reasons why you should be using GDI+, here are some:

  • Successor to GDI
  • Compatible with .NET
  • Optimizes many of the capabilities of GDI
  • Supports: Gradient Brushes, Independent Path Objects, Transformations and the Matrix Object, Scalable Regions, Alpha Blending and support for multiple image formats:
    • BMP
    • GIF
    • JPEG
    • Exif
    • PNG
    • TIFF
    • ICON
    • WMF
    • EMF

During my development of Windows GUI based applications with GDI+, I've come across the need to display animated GIFs, whilst GDI+ does not support displaying animated GIFs directly, in can be done with a little coding.

Implementation

Firstly lets look at drawing a simple image using GDI+.

void CMyWnd::OnPaint()
{
	CPaintDC dc(this);
	
	Graphics graphics(&dc); // Create a GDI+ graphics object

	Image image(L"Test.Gif"); // Construct an image
	
	graphics.DrawImage(&image, 0, 0, image.GetWidth(), image.GetHeight());	
		
}

Straight away we can see the simplistic C++ interface for using GDI objects. This makes it a sure fire way for using GDI objects. There is no need for using SelectObject to select GDI objects in and out of the device context.

For those of the readers who are not familiar with the format of an animated GIF, animated GIF is actually a series of GIF frames with a delay time associated each frame, therefore each frame can have a different delay time.

My implementation of encapsulating an animated GIF functionality derives a class called from ImageEx from the GDI+ Image class. The first task is to determine whether or not a GIF is of the animated kind. The following code demonstrates this:

bool ImageEx::TestForAnimatedGIF()
{
	UINT count = 0;
	count = GetFrameDimensionsCount();
	GUID* pDimensionIDs = new GUID[count];

	// Get the list of frame dimensions from the Image object.
	GetFrameDimensionsList(pDimensionIDs, count);

	// Get the number of frames in the first dimension.
	m_nFrameCount = GetFrameCount(&pDimensionIDs[0]);

	// Assume that the image has a property item of type PropertyItemEquipMake.
	// Get the size of that property item.
	int nSize = GetPropertyItemSize(PropertyTagFrameDelay);

	// Allocate a buffer to receive the property item.
	m_pPropertyItem = (PropertyItem*) malloc(nSize);

	GetPropertyItem(PropertyTagFrameDelay, nSize, m_pPropertyItem);


	delete pDimensionIDs;

	return m_nFrameCount > 1;
}
<!-- Info Task Footer -->

m_pPropertyItem->value is actually a pointer to an array of longs, each long is a delay time which corresponds to a GIF frame. Because GetPropertyItem returns a different size depending on what property using interested in, a Size is require and its the programmer responsibility to allocate and deallocate the memory associated with GetPropertyItem. The size is determined by calling GetPropertyItemSize supplying property tag your interested in.

Once the number of frames and delay times have been retrieved from the image, a thread is created which calls to DrawFrameGIF until the object destructs. See DrawFrameGIF below:

bool ImageEx::DrawFrameGIF()
{

	::WaitForSingleObject(m_hPause, INFINITE);

	GUID pageGuid = FrameDimensionTime;

	long hmWidth = GetWidth();
	long hmHeight = GetHeight();

	HDC hDC = GetDC(m_hWnd);
	if (hDC)
	{
		Graphics graphics(hDC);
		graphics.DrawImage(this, m_rc.left, m_rc.top, hmWidth, hmHeight);
		ReleaseDC(m_hWnd, hDC);
	}

	SelectActiveFrame(&pageGuid, m_nFramePosition++); 

	if (m_nFramePosition == m_nFrameCount)
		m_nFramePosition = 0;


	long lPause = ((long*) m_pPropertyItem->value)[m_nFramePosition] * 10;

	DWORD dwErr = WaitForSingleObject(m_hExitEvent, lPause);

	return dwErr == WAIT_OBJECT_0;
}

One other interesting aspect of this class is it has the ability of loading a image directly as a resource from an executable. I usually import my GIF into a project and give it a resource type of "GIF" and then rename the resource ID from a numeric constant to a string (see the example code).

Conclusion

If you familiar with the concepts and programming of GDI, GDI+ provides some advance features and the interface almost mirrors the .NET GDI namespace. The sample apps and code include the full listings for implementing animated GIF in your code applications. For code reference just search for GDI+ within the code. One thing I haven't included in this article is starting up and shutting the GDI+ subsystem.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

NormDroid
Software Developer (Senior) Software Kinetics
United Kingdom United Kingdom



Software Kinetics
are experts in developing customised and bespoke applications and have expertise in the development of desktop, mobile and internet applications on Windows.

We specialise in:

  • User Interface Design
  • Desktop Development
  • Windows Phone Development
  • Windows Presentation Framework
  • Windows Forms
  • Windows Communication Framework
  • Windows Services
  • Network Applications
  • Database Applications
  • Web Development
  • Web Services
  • Silverlight
  • ASP.net
 
Visit Software Kinetics
Follow on   Twitter

Comments and Discussions

 
GeneralMy vote of 3 PingroupMahdi Nejadsahebi30-Apr-11 21:13 
Questionone thread per gif, more gif picture will use more thread, and that's terrible PinmemberDavid_LoveCpp7-Oct-10 3:31 
QuestionProblem with speed for animate gif [modified] Pinmemberharturo12-Feb-10 11:06 
AnswerRe: Problem with speed for animate gif PinmemberGarth J Lancaster12-Feb-10 11:58 
AnswerRe: Problem with speed for animate gif [modified] Pinmemberharturo12-Feb-10 16:36 
AnswerRe: Problem with speed for animate gif: ===THANKS, DOUBT RESOLVED=== [modified] Pinmemberharturo16-Feb-10 21:23 
I find the solution in a code:
 
// PictureEx.cpp: implementation of the CPictureEx class.
//
// Picture displaying control with support for the following formats:
// GIF (including animated GIF87a and GIF89a), JPEG, BMP, WMF, ICO, CUR
//
// Written by Oleg Bykov (oleg_bykoff@rsdn.ru)
// Copyright (c) 2001
 
and in this part of his code:
 
               // if the delay time is too short (like in old GIFs), wait for 100ms
               if (m_arrFrames[m_nCurrFrame].m_nDelay < 5)
                    WaitForSingleObject(m_hExitEvent, 100);
               else
                    WaitForSingleObject(m_hExitEvent, 10*m_arrFrame[m_nCurrFrame].m_nDelay);
 
and this code traduced to my code say it:
 
                                    if pause retrived < 5 (like in old GIFs), then
                                       pause = 100
                                    else pause = pause * 10;
 

Then my code in order that:
 
               ULONG pause = ((ULONG*)m_pPropertyItem->value)[m_nFramePosition];
               if(pause < 5)
                    pause = 100;
               else
                    pause *= 10;
 
In this way the gif animation work well, like the rest applications. Like I want.
Thanks every body for you attention to my question. Doubt resolved.
 

-- Modified Wednesday, February 17, 2010 3:32 AM
GeneralRe: Problem with speed for animate gif: ===THANKS, DOUBT RESOLVED=== PingroupNorm .net16-Feb-10 21:35 
GeneralRe: Problem with speed for animate gif: ===THANKS, for your quickly 12 min. after Re=== Pinmemberharturo17-Feb-10 14:22 
GeneralRe: Problem with speed for animate gif: ===THANKS, for your quickly 12 min. after Re=== PingroupNorm .net17-Feb-10 20:36 
AnswerRe: Problem with speed for animate gif Pinmemberkwoitek4-Nov-10 2:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140718.1 | Last Updated 30 Jan 2002
Article Copyright 2002 by NormDroid
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid