How to Display a Bitmap in a WPF Image

106,541

I have used this snipped now to convert the Bitmap to a ImageSource:

BitmapImage BitmapToImageSource(Bitmap bitmap)
{
    using (MemoryStream memory = new MemoryStream())
    {
        bitmap.Save(memory, System.Drawing.Imaging.ImageFormat.Bmp);
        memory.Position = 0;
        BitmapImage bitmapimage = new BitmapImage();
        bitmapimage.BeginInit();
        bitmapimage.StreamSource = memory;
        bitmapimage.CacheOption = BitmapCacheOption.OnLoad;
        bitmapimage.EndInit();

        return bitmapimage;
    }
}
Share:
106,541
Gerret
Author by

Gerret

Updated on July 09, 2022

Comments

  • Gerret
    Gerret almost 2 years

    I want to implement a image editing program, but I can not display the Bitmap in my WPF. For the general editing I need a Bitmap. But I can not display that in a Image.

    private void MenuItemOpen_Click(object sender, RoutedEventArgs e)
    {
        OpenFileDialog openfiledialog = new OpenFileDialog();
    
        openfiledialog.Title = "Open Image";
        openfiledialog.Filter = "Image File|*.bmp; *.gif; *.jpg; *.jpeg; *.png;";
    
        if (openfiledialog.ShowDialog() == true)
        {
            image = new Bitmap(openfiledialog.FileName);
        }
    }
    

    I load the Image with a OpenFileDialog into the Bitmap. Now I want to set the picture in my WPF. Like so:

    Image.Source = image;
    

    I really need a Bitmap to get the color of a special pixel! I need a simple code snipped.

    Thank you for your help!

  • Gerret
    Gerret about 10 years
    This is not working for me. I need the Bitmap class to get the color of a special pixel.
  • Saverio Terracciano
    Saverio Terracciano about 10 years
    Check my answer, I updated it.
  • user3114639
    user3114639 almost 8 years
    (ImageSource)c.ConvertFrom(yourBitmap) results in a NullReferenceException
  • Nicolas Fall
    Nicolas Fall over 7 years
    why would someone put bitmapimage.Freeze() in here after .EndInit?
  • Gener4tor
    Gener4tor almost 5 years
    I get a NullReferenceException too