如何在WPF图像中显示位图

Ger*_*ret 25 c# wpf image bitmap

我想实现一个图像编辑程序,但我无法在WPF中显示Bitmap.对于一般编辑,我需要一个位图.但是我无法在图像中显示它.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我将带有OpenFileDialog的Image加载到Bitmap中.现在我想在我的WPF中设置图片.像这样:

Image.Source = image;
Run Code Online (Sandbox Code Playgroud)

我真的需要一个Bitmap来获得特殊像素的颜色!我需要一个简单的代码剪切.

谢谢您的帮助!

Ger*_*ret 68

我现在使用此剪切将Bitmap转换为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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么有人会在 `.EndInit` 之后把 `bitmapimage.Freeze()` 放在这里? (2认同)