【问题标题】:No transparency in Bitmap when loading from MemoryStream从 MemoryStream 加载时位图没有透明度
【发布时间】:2012-09-18 15:08:48
【问题描述】:

当我将Bitmap 写入文件并从文件中读取时,我得到了正确的透明度。

using (Bitmap bmp = new Bitmap(2, 2))
{
    Color col = Color.FromArgb(1, 2, 3, 4);
    bmp.SetPixel(0, 0, col);
    bmp.Save("J.bmp");
}

using (Bitmap bmp = new Bitmap("J.bmp"))
{
    Color col = bmp.GetPixel(0, 0);
    // Value of col.A = 1. This is right.
}

但如果我将Bitmap 写入MemoryStream 并从中读取MemoryStream,则透明度已被删除。所有 alpha 值都变为255

MemoryStream ms = new MemoryStream();
using (Bitmap bmp = new Bitmap(2, 2))
{
    Color col = Color.FromArgb(1, 2, 3, 4);
    bmp.SetPixel(0, 0, col);
    bmp.Save(ms, ImageFormat.Bmp);
}

using (Bitmap bmp = new Bitmap(ms))
{
    Color col = bmp.GetPixel(0, 0);
    // Value of col.A = 255. Why? I am expecting 1 here.
}

我希望将Bitmap 保存到MemoryStream 并以透明的方式读回。我该如何解决这个问题?

【问题讨论】:

  • new Bitmap(ms) 调用之前没有ms.position=0。不确定在这种情况下是否有问题,所以发表评论。

标签: c# bitmap memorystream


【解决方案1】:

问题是这一行:bmp.Save(ms, ImageFormat.Bmp)。 ImageFormat.Bmp 不支持 alpha 值,您可以将其更改为 ImageFormat.Png 以获得相同的效果。

【讨论】:

  • +1 到.Png 建议。从流中读取位图实际上确实在流上搜索,这有点令人惊讶,但似乎ms.position=0 在我期望的new Bitmap(ms) 之前。
【解决方案2】:

AFAIK BMP 格式不支持透明度。检查将格式更改为例如 PNG:

bmp.Save(ms, ImageFormat.Png);

但是,您可以索引一个 .bmp,它将在第 256 个位置添加透明颜色。问题是,bmp 的很多图片要求是 24 位和 32 位,而透明的索引图片只能转换为 16 位。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-03
    • 2018-04-02
    • 1970-01-01
    相关资源
    最近更新 更多