#699 – Converting an Image Control to a Bitmap

You may want to work with the image from an Image control as a standard Windows bitmap.  You can convert the System.Windows.Controls.Image to a System.Drawing.Bitmap as follows (imgLife is an Image control):

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            RenderTargetBitmap rtBmp = new RenderTargetBitmap((int)imgLife.ActualWidth, (int)imgLife.ActualHeight,
                96.0, 96.0, PixelFormats.Pbgra32);

            imgLife.Measure(new System.Windows.Size((int)imgLife.ActualWidth, (int)imgLife.ActualHeight));
            imgLife.Arrange(new Rect(new System.Windows.Size((int)imgLife.ActualWidth, (int)imgLife.ActualHeight)));

            rtBmp.Render(imgLife);

            PngBitmapEncoder encoder = new PngBitmapEncoder();
            MemoryStream stream = new MemoryStream();
            encoder.Frames.Add(BitmapFrame.Create(rtBmp));

            // Save to memory stream and create Bitamp from stream
            encoder.Save(stream);
            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(stream);

            // Demonstrate that we can do something with the Bitmap
            bitmap.Save(@"D:\Temp\Life.png", ImageFormat.Png);

            // Optionally, if we didn't need Bitmap object, but
            // just wanted to render to file, we could:
            //encoder.Save(new FileStream(@"D:\Temp\Life-Other.png", FileMode.Create));
        }

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

3 Responses to #699 – Converting an Image Control to a Bitmap

  1. Pingback: Dew Drop – November 27, 2012 (#1,450) | Alvin Ashcraft's Morning Dew

  2. Sergio Gutiérrez. says:

    Hi dude,

    Many thanks for this code!! i search for several days something like this, i found other codes but not works for my need(Kinect WPF projects)

    Best regards 🙂

  3. anver sadat says:

    thanks a lot….

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: