Souvik Ghosh
Souvik Ghosh

Reputation: 4616

Image fails to save in Parallel.For loop

I am using Parallel.For loop to process some images. When I try to save the image, sometimes I get an exception-

a generic error occurred in gdi+

Some images gets saves then this exception comes randomly after saving few files.

Below is my code-

Parallel.For(0, 14, cnt =>
{
    using (Bitmap originalImage = (Bitmap)Bitmap.FromFile(@imagePath))
    {
        for (int i = 0; i < originalImage.Width; i++)
        {
            for (int x = 0; x < originalImage.Height; x++)
            {
                System.Drawing.Color oc = originalImage.GetPixel(i, x);
                int gray = (int)((oc.R * 0.3) + (oc.G * 0.59) + (oc.B * 0.11));
                System.Drawing.Color nc = System.Drawing.Color.FromArgb(oc.A, gray, gray, gray);
                originalImage.SetPixel(i, x, nc);
            }
        }
        try
        {
            //Bitmap grayscaleImage = originalImage;
            //grayscaleImage.Save(@processesImagesPath + DateTime.Now.ToString("dd-MM-yyyy_hh.mm.ss") + ".jpg");  //line of exception

            //above lines did not work

            Monitor.Enter(originalImage);
            originalImage.Save(@processesImagesPath + DateTime.Now.ToString("dd-MM-yyyy_hh.mm.ss") + ".jpg");  //line of exception
        }
        finally
        {
            Monitor.Exit(originalImage);
        }
    }   
});

Upvotes: 1

Views: 363

Answers (1)

Backs
Backs

Reputation: 24913

DateTime.Now.ToString("dd-MM-yyyy_hh.mm.ss") - two images can be saved in one second, you will get an error. Create more unique filename. For example:

var filename = DateTime.Now.ToString("dd-MM-yyyy_hh.mm.ss") + cnt

Upvotes: 1

Related Questions