如何在WPF图像中显示位图

45

我想实现一个图片编辑程序,但是我无法在我的WPF中显示位图。为了进行一般的编辑,我需要一个位图,但是我无法将其显示在一个图像中。

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);
    }
}

我使用 OpenFileDialog 将图像加载到 Bitmap 中。现在我想将图片设置到我的 WPF 中。方法如下:

Image.Source = image;

我真的需要一个位图来获取特定像素的颜色! 我需要一个简单的代码片段。

谢谢你的帮助!


2
如果您想保留System.Drawing.Bitamp而不使用System.Windows.Media.Imaging.BitmapImage,那么请查看以下问题:https://dev59.com/1XVD5IYBdhLWcg3wE3bz - dkozl
2个回答

109

我现在使用这个片段将位图转换为图像源:

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;
    }
}

2
为什么有人会在 .EndInit 之后加上 bitmapimage.Freeze() - Maslow
@Maslow 当它被另一个线程拥有时,允许阅读它。 - undefined

-1

这应该可以:

ImageSource imgSource = new BitmapImage(new Uri("HERE GOES YOUR URI"));

image1.Source = imgSource; //image1 is your control

如果您需要使用Bitmap类,请尝试使用以下代码:
 public ImageSource imageSourceForImageControl(Bitmap yourBitmap)
{
 ImageSourceConverter c = new ImageSourceConverter();
 return (ImageSource)c.ConvertFrom(yourBitmap);
}

2
这对我不起作用。我需要使用Bitmap类来获取特定像素的颜色。 - Gerret
检查我的答案,我更新了它。 - Saverio Terracciano
10
(ImageSource)c.ConvertFrom(yourBitmap) 导致了一个 NullReferenceException - user3114639
我也遇到了NullReferenceException异常。 - Gener4tor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接