question

sharonglipman-9594 avatar image
0 Votes"
sharonglipman-9594 asked sharonglipman-9594 commented

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

 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 ?


dotnet-csharpwindows-wpfdotnet-wpf-xaml
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

Castorix31 avatar image
1 Vote"
Castorix31 answered sharonglipman-9594 commented

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);
     }
 }
· 5
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Working great.

What if I want to replace the new images with the old ones ? I mean same folder but each time converting one to delete one so in the end there will be only the _new gif's ?

0 Votes 0 ·

You can add at the end, in the loop :

  System.IO.File.Delete(files[i]);

and by changing the part with BitmapImage with the method explained at : .NET, WPF – BitmapImage File Locking
(otherwise you cannot delete the original file because it is locked)



1 Vote 1 ·

I added already at the end of the loop File.Delete but it says the file is busy.

I read now the link you provided but you already making instance each time for the bi variable.
Can you show me how to make the part with the BitmapImage ?

0 Votes 0 ·
Show more comments