How to: Encode and Decode a GIF Image

 

The following examples show how to decode and encode a Graphics Interchange Format (GIF) image using the specific GifBitmapDecoder and GifBitmapEncoder objects.

This example demonstrates how to decode a GIF image using a GifBitmapDecoder from a FileStream.

            ' Open a Stream and decode a GIF image
            Dim imageStreamSource As New FileStream("tulipfarm.gif", FileMode.Open, FileAccess.Read, FileShare.Read)
            Dim decoder As New GifBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default)
            Dim bitmapSource As BitmapSource = decoder.Frames(0)

            ' Draw the Image
            Dim myImage As New Image()
            myImage.Source = bitmapSource
            myImage.Stretch = Stretch.None
            myImage.Margin = New Thickness(20)

This example demonstrates how to encode a BitmapSource into a GIF image using a GifBitmapEncoder.

            Dim width As Integer = 128
            Dim height As Integer = width
            Dim stride As Integer = CType(width / 8, Integer)
            Dim pixels(height * stride) As Byte

            ' Define the image palette
            Dim myPalette As BitmapPalette = BitmapPalettes.WebPalette

            ' Creates a new empty image with the pre-defined palette
            Dim image As BitmapSource = System.Windows.Media.Imaging.BitmapSource.Create(width, height, 96, 96, PixelFormats.Indexed1, myPalette, pixels, stride)
            Dim stream As New FileStream("new.gif", FileMode.Create)
            Dim encoder As New GifBitmapEncoder()
            Dim myTextBlock As New TextBlock()
            myTextBlock.Text = "Codec Author is: " + encoder.CodecInfo.Author.ToString()
            encoder.Frames.Add(BitmapFrame.Create(image))
            encoder.Save(stream)

Imaging Overview

Show: