How can I convert image file on the hard disk to gif in wpf ?

sharon glipman 441 Reputation points
2021-10-13T21:31:59.63+00:00
private void Button_Click(object sender, RoutedEventArgs e)
            {
                var img = new BitmapImage();
                string[] files = System.IO.Directory.GetFiles(@"d:\Images", "*.gif");
                for(int i = 0; i < files.Length; i++)
                {

                }
            }

On the hard disk I downloaded some images and saved them as .gif but I need to convert them to real gif format. In winforms I used Image.save and stream but in wpf I'm not sure how to convert the files.

Not sure if this is needed at all :

var img = new BitmapImage();

And I'm getting the files and loop over them but not sure how to make the conversion in the loop ?

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,665 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,193 questions
XAML
XAML
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
760 questions
0 comments No comments
{count} votes

Accepted answer
  1. Castorix31 81,446 Reputation points
    2021-10-13T22:01:40.88+00:00

    You can do for example :

    BitmapImage bi = null;
    string[] files = System.IO.Directory.GetFiles(@"d:\Images", "*.gif");
    for (int i = 0; i < files.Length; i++)
    {
        bi = new BitmapImage();
        bi.BeginInit();
        bi.UriSource = new Uri(files[i], UriKind.RelativeOrAbsolute);
        bi.EndInit();
    
        GifBitmapEncoder gif = new GifBitmapEncoder();
        gif.Frames.Add(BitmapFrame.Create(bi));
        string sPath = System.IO.Path.GetDirectoryName(files[i]);
        string sFilename = System.IO.Path.GetFileNameWithoutExtension(files[i]);
        string sNewName = sPath  + @"\" + sFilename + "_new.gif";
        using (System.IO.Stream stm = System.IO.File.Create(sNewName)) 
        {
            gif.Save(stm);
        }
    }
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful