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

本文关键字:图像 背景 黑色 我的 位图 转换 ImageSource | 更新日期: 2023-09-27 18:18:04

这是我的代码:

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

bitmaptoimagesourcecconverter的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>

如何修复黑色背景?

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

我使用@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;
  }
}