0

The error is on the line:

for (int x = 0; x < myList.Count(); x++)

The x++is painted with green.

Im using backgroundoworker and I used this code same code in another form before without a backgroundworker and it worked good. Now in the other form im using a click button event to show() this form and I want to use a progressBar1 to show the progress of the backgroundowrker work.

I used now try and catch inside this for loop and it went to the catch point and showed me the error. The full exception message is:

 at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams)
 at System.Drawing.Image.Save(String filename, ImageFormat format)
 at mws.Animation_Radar_Preview.backGroundWorker1_DoWork(Object sender, DoWorkEventArgs e) in D:\C-Sharp\Download File\Downloading-File-Project-Version-012\Downloading File\Animation_Radar_Preview.cs:line 163

gifImages isnt null. 

This is the full code of this form:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using DannyGeneral;
using unfreez_wrapper;


namespace mws
{
    public partial class Animation_Radar_Preview : Form
    {
        int mtpStart;
        int mtpEnd;
        Picturebox1_Fullscreen pb1;
        string radar_images_download_directory;
        string tempRadarPngToGifDirectory;
        int numberOfFiles;
        UnFreezWrapper unfreez;
        string path_exe;
        List<string> myList;
        string previewDirectory;
        int animatedGifSpeed;
        bool loop;
        string nameOfStartFile;
        string nameOfEndFile;
        string previewFileName;
        BackgroundWorker backGroundWorker1;
        Image img;
        private MemoryStream _memSt = null;
        public Animation_Radar_Preview()
        {
            InitializeComponent();
            mtpStart = Picturebox1_Fullscreen.mtp1Start;
            mtpEnd = Picturebox1_Fullscreen.mtp1End;
            animatedGifSpeed = Picturebox1_Fullscreen.animatedSpeed;
            loop = Picturebox1_Fullscreen.looping;
            pb1 = new Picturebox1_Fullscreen();
            radar_images_download_directory = Options_DB.Get_Radar_Images_Download_Directory();
            path_exe = Path.GetDirectoryName(Application.LocalUserAppDataPath);
            tempRadarPngToGifDirectory = path_exe + "\\" + "tempRadarPngToGifDirectory";
            if (Directory.Exists(tempRadarPngToGifDirectory))
            {
            }
            else
            {
                Directory.CreateDirectory(tempRadarPngToGifDirectory);
            }
            previewDirectory = path_exe + "\\" + "previewDirectory";
            if (Directory.Exists(previewDirectory))
            {
            }
            else
            {
                Directory.CreateDirectory(previewDirectory);
            }
            previewFileName = previewDirectory + "\\" + "preview.gif";
            loop = false;
            animatedGifSpeed = 0;
            unfreez = new UnFreezWrapper();
            backGroundWorker1 = new BackgroundWorker();
            backGroundWorker1.WorkerSupportsCancellation = true;
            this.backGroundWorker1.WorkerReportsProgress = true;
            backGroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backGroundWorker1_ProgressChanged);
            backGroundWorker1.DoWork += new DoWorkEventHandler(backGroundWorker1_DoWork);
            backGroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backGroundWorker1_RunWorkerCompleted);
            backGroundWorker1.RunWorkerAsync();
            progressBar1.Value = 0;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            DialogResult result1;
            result1 = new DialogResult();
            SaveFileDialog sd = new SaveFileDialog();
            sd.Title = "Select a folder to save the animated gif to";
            sd.InitialDirectory = "c:\\";
            sd.FileName = null;
            sd.Filter = "Gif File|*.gif;*.jpg|Gif|*.gif";
            sd.FilterIndex = 1;
            sd.RestoreDirectory = true;
            result1 = sd.ShowDialog();
            string file1 = sd.FileName;
            if (result1 == DialogResult.OK)
            {
                File.Move(previewFileName, file1);
            }
        }

        public void pictureBoxImage(string pbImage)
        {
            Image img2 = null;
            try
            {
                using (img = Image.FromFile(pbImage))
                {
                    //get the old image thats loaded from the _memSt memorystream
                    //and dispose it
                    Image i = this.pictureBox1.Image;
                    this.pictureBox1.Image = null;

                    if (i != null)
                        i.Dispose();

                    //grab the old stream
                    MemoryStream m = _memSt;

                    //save the new image to this stream
                    _memSt = new MemoryStream();
                    img.Save(_memSt, System.Drawing.Imaging.ImageFormat.Gif);

                    if (m != null)
                        m.Dispose();

                    //create our image to display
                    img2 = Image.FromStream(_memSt);
                }

                if (img2 != null)
                    pictureBox1.Image = img2;
                label2.Text = numberOfFiles.ToString();
                label6.Text = nameOfStartFile.ToString();
                label4.Text = nameOfEndFile.ToString();
                //File.Delete(pbImage);
            }
            catch(Exception err)
            {
                Logger.Write("Animation Error >>>   " + err);
            }
        }

        private void backGroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
        }

        private void backGroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            List<string> myGifList;
            Image gifImages = null;
            //button1.Enabled = false;
            Animation_Radar_Preview ap = new Animation_Radar_Preview();
            //ap.FormClosing += new FormClosingEventHandler(ap_FormClosing);
            FileInfo[] fi;
            DirectoryInfo dir1 = new DirectoryInfo(radar_images_download_directory);
            fi = dir1.GetFiles("*.png");
            myList = new List<string>();
            myGifList = new List<string>();
            for (int i = mtpStart; i < mtpEnd; i++)
            {
                myList.Add(fi[i].FullName);
            }
            for (int x = 0; x < myList.Count(); x++)
            {
                try
                {
                    gifImages = Image.FromFile(myList[x]);
                    gifImages.Save(tempRadarPngToGifDirectory + "\\" + x.ToString("D6") + ".Gif", System.Drawing.Imaging.ImageFormat.Gif);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(x.ToString() + "\r\n" + (gifImages == null).ToString() + "\r\n" + ex.Message);
                }
            }

            myGifList = new List<string>();
            dir1 = new DirectoryInfo(tempRadarPngToGifDirectory);
            fi = dir1.GetFiles("*.gif");
            nameOfStartFile = fi[0].Name;
            for (int i = 0; i < fi.Length; i++)
            {
                myGifList.Add(fi[i].FullName);
                //backGroundWorker1.ReportProgress(i);
                nameOfEndFile = fi[i].Name.Length.ToString();
            }
            numberOfFiles = myGifList.Count();
            unfreez.MakeGIF(myGifList, previewFileName, animatedGifSpeed, loop);
            /*this.Invoke((MethodInvoker)delegate
            {
                pictureBoxImage(previewFileName); 
            });*/
        }

        private void backGroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            pictureBoxImage(previewFileName);
        }
    }
}
Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
Daniel Bogdan
  • 51
  • 1
  • 10

1 Answers1

1

I'm not entirely sure what is going wrong, especially as you say this same code worked previously — but it is not clear whether it worked with the same set of images.

Anyhow, the documentation for the Save method says that an ExternalException will be thrown in one of two situations:

  1. Image was saved with the wrong format.
  2. Image is saved to the file it was created from.

It cannot be that you are saving over the file because you are changing its extension, so it must be the wrong format. What this actually means is not clear. Perhaps one of the source images is using capabilities of the PNG format that cannot be converted to GIF, e.g. alpha channel transparency.

If I may take a moment to make some other suggestions too:

if (Directory.Exists(tempRadarPngToGifDirectory))
{
}
else
{
    Directory.CreateDirectory(tempRadarPngToGifDirectory);
}

The empty 'success' case is not required if you invert the logic:

if (!Directory.Exists(tempRadarPngToGifDirectory)
{
    Directory.CreateDirectory(tempRadarPngToGifDirectory);
}

Code that manipulates file paths such as the following:

tempRadarPngToGifDirectory = path_exe + "\\" + "tempRadarPngToGifDirectory";

You should consider using the Path class as this will handle the edge cases better and make more portable code:

tempRadarPngToGifDirectory = Path.Combine(path_exe, "tempRadarPngToGifDirectory");
Paul Ruane
  • 37,459
  • 12
  • 63
  • 82
  • Agree - you get this error when you try to save an image to a file format the image can't be saved as. – dash Dec 13 '11 at 00:16
  • I cant convert png to gif ? Or maybe i need to do it in another way then Save ? – Daniel Bogdan Dec 13 '11 at 00:28
  • I am suggesting that perhaps the particular PNG file uses some advanced feature that the .NET `Image` class is unable to convert such as alpha channel transparency or animation or suchlike. Have you had a look at the image it is having trouble with the see if there is anything unusual about it? – Paul Ruane Dec 13 '11 at 00:35
  • Paul no the images are ok i saw them in the directory size are ok and i can edit the images and i see them all as Gif files the type is gif. So its doing the convertion but also throwing many errors in the messagebox in the catch area all the errors say this generic error and now it give me another error say cant create gif file i guess its connecting to the unfreez.makegif so there is a problem with the files maybe but i dont know what is the problem excatly. – Daniel Bogdan Dec 13 '11 at 00:51
  • I'm sorry, bit confused. Are you saying that it is creating the files but also throwing exceptions? Could simply be that the file names it is trying to save to already exist? (It seems ExternalException wraps any error thrown by the underlying system call.) – Paul Ruane Dec 13 '11 at 00:54
  • Paul no the files arent exist i deleted manualy and tried and same errors. – Daniel Bogdan Dec 13 '11 at 02:19
  • The convertion from png to gif isnt the problem. – Daniel Bogdan Dec 13 '11 at 02:47
  • for (int i = 0; i < images.Length; i++) { newimages = Image.FromFile(images[i]); newimages.Save(destinationDirectory + "\\" + i.ToString("D6") /*x.ToString("D6")* */+ ".Gif", System.Drawing.Imaging.ImageFormat.Gif); if (i == 100) { MessageBox.Show("converted"); break; } } – Daniel Bogdan Dec 13 '11 at 02:48
  • Its a new project for test and this code this is working. perfect i can edit see use the new files in the directory all the files are type .gif but as soon as i used backgroundowrker in the other project the errors started. So for sure converting png to gif os possible as you can see in the example but maybe something with the backgroundworker make the problems i dont know i just tested and the convertion shouldnt be a problem. And i used also with Save and no errors i tried few times. – Daniel Bogdan Dec 13 '11 at 02:50