question

divyadhayalan-4358 avatar image
0 Votes"
divyadhayalan-4358 asked divyadhayalan-4358 commented

Reduce time consumption while converting Image to ImageSource

Hi,

We are facing average of 5.5 seconds time consumption while converting an Image with size(17712, 24792) into ImageSource. Kindly check the below code snippet and please suggest me how to reduce the time consumption?

 private void ImageToImageSource_Click(object sender, RoutedEventArgs e)
         {
             ImageSource imgsource = null;
             System.Drawing.Image image = new System.Drawing.Bitmap(17712, 24792);
             System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(image);
             graphics.FillRectangle(System.Drawing.Brushes.White, new System.Drawing.Rectangle(0, 0, (int)(image.Width), (int)(image.Height)));
             Stopwatch sw = new Stopwatch();
             sw.Start();
             using (Stream ms = new MemoryStream())
             {
                 image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                 var decoder = BitmapDecoder.Create(ms, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
                 imgsource = decoder.Frames[0];
             }
             sw.Stop();
             Debug.WriteLine("Elapsed: " + sw.ElapsedMilliseconds.ToString());
         }

Regards,
Divya

dotnet-csharpwindows-wpf
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

Viorel-1 avatar image
0 Votes"
Viorel-1 answered divyadhayalan-4358 commented

Check if the next approach works:

 image.Save( ms, System.Drawing.Imaging.ImageFormat.Png );
 var bi = new BitmapImage( );
 bi.BeginInit( );
 bi.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
 bi.CacheOption = BitmapCacheOption.OnLoad;
 bi.StreamSource = ms;
 bi.EndInit( );
 imgsource = bi;

Also try ImageFormat.Bmp.

· 1
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.

Hi Viorel-1,

Thank you for the suggestion, but the time consumption remains the same with the suggested code.

Please let me know if you have any other suggestions for how to reduce the time it takes to convert an image to an image source.

Regards,
Divya

0 Votes 0 ·