【C#/WPF】图像数据格式转换时,透明度丢失的问题

简介: 原文:【C#/WPF】图像数据格式转换时,透明度丢失的问题 问题:工作中涉及到图像的数据类型转换,经常转着转着发现,到了哪一步图像的透明度丢失了! 例如,Bitmap转BitmapImage的经典代码如下: ...
原文: 【C#/WPF】图像数据格式转换时,透明度丢失的问题

问题:工作中涉及到图像的数据类型转换,经常转着转着发现,到了哪一步图像的透明度丢失了!


例如,Bitmap转BitmapImage的经典代码如下:

public static BitmapImage BitmapToBitmapImage(System.Drawing.Bitmap bitmap)
{
    using (MemoryStream stream = new MemoryStream())
    {
        bitmap.Save(stream, ImageFormat.Bmp);

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

使用时发现,如果一张图片四周是透明的,那么转出来的BitmapImage图像四周透明部分会被自动填充为黑色的!解决办法在于修改Bitmap保存时选择的格式,把Bmp改为Png即可。

bitmap.Save(stream, ImageFormat.Png);

同样,类似的经验教训还有如下,在图片数据格式转换时,常常要注意是否保留有α通道透明度数据,
比如在ImageSource转为System.Drawing.Bitmap的方法:

public static System.Drawing.Bitmap ImageSourceToBitmap(ImageSource imageSource)
{
    BitmapSource m = (BitmapSource)imageSource;

    System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(m.PixelWidth, m.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

    System.Drawing.Imaging.BitmapData data = bmp.LockBits(
    new System.Drawing.Rectangle(System.Drawing.Point.Empty, bmp.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

    m.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
    bmp.UnlockBits(data);

    return bmp;
}

要非常细心,看清楚选择的格式

System.Drawing.Imaging.PixelFormat.Format32bppPArgb; // 带有α通道的
System.Drawing.Imaging.PixelFormat.Format32bppRgb;   // 不带α通道的
目录
相关文章
|
22天前
|
数据采集 JavaScript C#
C#图像爬虫实战:从Walmart网站下载图片
C#图像爬虫实战:从Walmart网站下载图片
|
13天前
|
C#
C# WPF 中 外部图标引入iconfont,无法正常显示问题 【小白记录】
本文介绍了在C# WPF应用程序中引入外部iconfont图标时可能遇到的显示问题及其解决方法:1) 检查资源路径和引入格式是否正确,确保字体文件引用格式为“#xxxx”,并正确指向字体文件位置;2) 确保图标资源被包含在程序集中,通过设置字体文件的生成操作为Resource(资源)来实现。
C# WPF 中 外部图标引入iconfont,无法正常显示问题 【小白记录】
|
21天前
|
编解码 C# 数据库
C# + WPF 音频播放器 界面优雅,体验良好
【9月更文挑战第18天】这是一个用 C# 和 WPF 实现的音频播放器示例,界面简洁美观,功能丰富。设计包括播放/暂停按钮、进度条、音量控制滑块、歌曲列表和专辑封面显示。功能实现涵盖音频播放、进度条控制、音量调节及歌曲列表管理。通过响应式设计、动画效果、快捷键支持和错误处理,提升用户体验。可根据需求扩展更多功能。
|
1天前
|
XML JSON 前端开发
C#使用HttpClient四种请求数据格式:json、表单数据、文件上传、xml格式
C#使用HttpClient四种请求数据格式:json、表单数据、文件上传、xml格式
16 0
|
2月前
|
C#
C# WPF 将第三方DLL嵌入 exe
C# WPF 将第三方DLL嵌入 exe
37 0
|
2月前
|
前端开发 C# 容器
WPF/C#:实现导航功能
WPF/C#:实现导航功能
46 0
|
2月前
|
设计模式 测试技术 C#
WPF/C#:在WPF中如何实现依赖注入
WPF/C#:在WPF中如何实现依赖注入
46 0
|
2月前
|
前端开发 C# Windows
WPF/C#:如何实现拖拉元素
WPF/C#:如何实现拖拉元素
44 0
|
2月前
|
存储 C# 索引
WPF/C#:BusinessLayerValidation
WPF/C#:BusinessLayerValidation
30 0
|
2月前
|
C#
WPF/C#:数据绑定到方法
WPF/C#:数据绑定到方法
34 0