2

我有一些问题。我正在尝试将 png-image 从资源加载到我的 viewModel 中的 BitmapImage 属性,如下所示:

Bitmap bmp = Resource1.ResourceManager.GetObject(String.Format("_{0}",i)) as Bitmap;
MemoryStream ms = new MemoryStream();
bmp.Save(ms, ImageFormat.Bmp);
BitmapImage bImg = new BitmapImage();

bImg.BeginInit();
bImg.StreamSource = new MemoryStream(ms.ToArray());
bImg.EndInit();

this.Image = bImg;

但是当我这样做时,我失去了图像的透明度。所以问题是如何在不损失透明度的情况下从资源中加载 png 图像?谢谢,帕维尔。

4

4 回答 4

7

Ria 的回答帮助我解决了透明度问题。这是对我有用的代码:

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;
  }
}
于 2014-05-28T18:58:24.220 回答
3

这是因为BMP文件格式不支持透明度,而PNG文件格式支持。如果你想要透明度,你将不得不使用PNG.

尝试ImageFormat.Png保存。

于 2012-07-18T08:47:43.620 回答
0

BitmapImage这通常是由不支持的 64 位深度 PNG 图像引起的。Photoshop 似乎错误地将这些显示为 16 位,因此您需要使用 Windows 资源管理器进行检查:

  • 右键单击该文件。
  • 单击属性。
  • 转到详细信息选项卡。
  • 寻找“位深度”——它通常在图像部分,有宽度和高度。

如果显示为 64,则需要使用 16 位深度重新编码图像。我建议使用Paint.NET,因为它可以正确处理 PNG 位深度。

于 2012-07-18T07:58:19.030 回答
0

我查看了这篇文章以找到与此处相同的透明度问题的答案。

但后来我看到给出的示例代码,只是想分享这段代码来从资源加载图像。

Image connection = Resources.connection;

使用这个我发现我不需要将我的图像重新编码为 16 位。谢谢。

于 2012-12-18T09:09:27.320 回答