将位图转换为ImageSource使我的图像背景变黑

petko_stankoski

这是我的代码:

<Image>
    <Image.Source>
        <Binding Source="{x:Static properties:Resources.myLogo}" Converter="{StaticResource BitmapToImageSourceConverter}" />
    </Image.Source>
</Image>

BitmapToImageSourceConverter的Convert方法就是这样的:

public object Convert(object value, Type targetType, object parameter,
        System.Globalization.CultureInfo culture)
    {
        MemoryStream ms = new MemoryStream();
        ((System.Drawing.Bitmap)value).Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
        BitmapImage image = new BitmapImage();
        image.BeginInit();
        ms.Seek(0, SeekOrigin.Begin);
        image.StreamSource = ms;
        image.EndInit();

        return image;
    }

图像以应有的方式显示,但背景为黑色。我试图像这样修复它:

<StackPanel Width="230" Height="80" Grid.Column="0" Margin="85 -40 0 0" HorizontalAlignment="Left" VerticalAlignment="Bottom" Background="Transparent">
    <Image>
        <Image.Source>
            <Binding Source="{x:Static properties:Resources.myLogo}" Converter="{StaticResource BitmapToImageSourceConverter}" />
        </Image.Source>
    </Image>
</StackPanel>

如何解决黑色背景?

petko_stankoski

我在这里使用@Dean的答案修复了它:从PNG到BitmapImage。透明度问题。

public BitmapImage ToBitmapImage(Bitmap bitmap)
{
  using (MemoryStream stream = new MemoryStream())
  {
    bitmap.Save(stream, ImageFormat.Png); // Was .Bmp, but this did not show a transparent background.

    stream.Position = 0;
    BitmapImage result = new BitmapImage();
    result.BeginInit();
    // According to MSDN, "The default OnDemand cache option retains access to the stream until the image is needed."
    // Force the bitmap to load right now so we can dispose the stream.
    result.CacheOption = BitmapCacheOption.OnLoad;
    result.StreamSource = stream;
    result.EndInit();
    result.Freeze();
    return result;
  }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

如何将图像转换为 ImageSource

来自分类Dev

如何将图标(位图)转换为ImageSource?

来自分类Dev

将整个布局转换为图像/位图

来自分类Dev

将图像从 RecyclerView 转换为位图

来自分类Dev

如何将位图图像转换为mat图像

来自分类Dev

如何将位图图像转换为Emgu图像?

来自分类Dev

如何将位图图像转换为Mat图像

来自分类Dev

将Listview项目转换为单个位图图像

来自分类Dev

将位图转换为Java中的mat以进行图像处理

来自分类Dev

将特定的位图图像颜色转换为透明

来自分类Dev

将图像转换为位图并减小其大小

来自分类Dev

如何将劣质位图图像转换为矢量?

来自分类Dev

将Listview项目转换为单个位图图像

来自分类Dev

裁剪后如何将图像转换为位图?

来自分类Dev

NumPy将8位图像转换为16/32位图像

来自分类Dev

将byte []转换为位图

来自分类Dev

将ExpandableListview转换为位图

来自分类Dev

将byte []转换为位图

来自分类Dev

将MessageBoxImage转换为ImageSource WPF

来自分类Dev

是什么在我的代码中使图像的背景变黑?

来自分类Dev

将opencv图像转换为gdi位图不起作用取决于图像大小

来自分类Dev

将32位图像转换为黑白黑白图像时遇到问题

来自分类Dev

如何将位图图像转换为.pcx格式以在Zebra打印机中打印图像

来自分类Dev

如何将24位JPEG图像转换为8位图像?

来自分类Dev

字符转换为位图图像C#

来自分类Dev

将图像视图背景设置为位图

来自分类Dev

将图像视图背景设置为位图

来自分类Dev

将Div背景图像转换为链接

来自分类Dev

SIGSEGV,同时将1位图像数据转换为8位