Reduce time consumption while converting Image to ImageSource

divya dhayalan 1 Reputation point
2021-07-22T15:32:06.517+00:00

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

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

1 answer

Sort by: Most helpful
  1. Viorel 122.6K Reputation points
    2021-07-22T18:21:45.227+00:00

    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.


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.