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 ?

Developer technologies | Windows Presentation Foundation
Developer technologies | XAML
Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Castorix31 90,686 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

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.