共用方式為


HOW TO:編碼和解碼 GIF 影像

更新:2007 年 11 月

下列範例示範如何使用特定的 GifBitmapDecoderGifBitmapEncoder 物件,對圖形交換格式 (GIF) 影像進行解碼和編碼。如需完整範例,請參閱 GIF 編碼器和解碼器範例

範例

此範例示範如何使用 FileStream 中的 GifBitmapDecoder,對 GIF 影像進行解碼。

' 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)
// Open a Stream and decode a GIF image
Stream imageStreamSource = new FileStream("tulipfarm.gif", FileMode.Open, FileAccess.Read, FileShare.Read);
GifBitmapDecoder decoder = new GifBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
BitmapSource bitmapSource = decoder.Frames[0];

// Draw the Image
Image myImage = new Image();
myImage.Source = bitmapSource;
myImage.Stretch = Stretch.None;
myImage.Margin = new Thickness(20);

此範例示範如何使用 GifBitmapEncoder,將 BitmapSource 編碼成 GIF 影像。

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)
int width = 128;
int height = width;
int stride = width / 8;
byte[] pixels = new byte[height * stride];

// Define the image palette
BitmapPalette myPalette = BitmapPalettes.WebPalette;

// Creates a new empty image with the pre-defined palette

BitmapSource image = BitmapSource.Create(
    width,
    height,
    96,
    96,
    PixelFormats.Indexed1,
    myPalette,
    pixels,
    stride);

FileStream stream = new FileStream("new.gif", FileMode.Create);
GifBitmapEncoder encoder = new GifBitmapEncoder();
TextBlock myTextBlock = new TextBlock();
myTextBlock.Text = "Codec Author is: " + encoder.CodecInfo.Author.ToString();
encoder.Frames.Add(BitmapFrame.Create(image));
encoder.Save(stream);

請參閱

概念

影像處理概觀