【问题标题】:How to Display a Bitmap in a WPF Image [duplicate]如何在 WPF 图像中显示位图 [重复]
【发布时间】:2014-04-25 07:36:24
【问题描述】:

我想实现一个图像编辑程序,但我无法在我的 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 的图像加载到位图中。现在我想在我的 WPF 中设置图片。像这样:

Image.Source = image;

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

感谢您的帮助!

【问题讨论】:

标签: c# wpf image bitmap


【解决方案1】:

我现在已使用此片段将位图转换为 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;
    }
}

【讨论】:

  • 为什么有人会把bitmapimage.Freeze()放在.EndInit之后?
【解决方案2】:

应该这样做:

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

【讨论】:

  • 这对我不起作用。我需要 Bitmap 类来获取特殊像素的颜色。
  • 检查我的答案,我更新了。
  • (ImageSource)c.ConvertFrom(yourBitmap) 导致NullReferenceException
  • 我也得到了 NullReferenceException
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-30
  • 2017-06-28
  • 2011-06-23
  • 1970-01-01
  • 1970-01-01
  • 2022-11-16
  • 1970-01-01
相关资源
最近更新 更多