c# - 为什么 WriteableBitmap 不能直接写入图像字节?
问题描述
我从通过 minicap 连续发送的套接字接收图像字节。当我将字节保存到图像时,图像可以正常打开。但是当我将字节渲染到 WriteableBitmap 时,它不起作用,代码如下:
void DrawUI(ref byte[] frameBody)
{
try
{
writeableBitmap.WritePixels(new Int32Rect(0, 0, 1080, 1920), frameBody, writeableBitmap.BackBufferStride, 0);
}
catch(Exception e)
{
Console.WriteLine($"catch a exception {e.Message}");
}
}
当我在下面修改它时,它可以正常工作,问题是我不想做任何转换,因为速度很重要。
void DrawUI(ref byte[] frameBody)
{
try
{
BitmapSource bms = (BitmapSource)new ImageSourceConverter().ConvertFrom(frameBody);
var bytesPerPixel = bms.Format.BitsPerPixel / 8;
var stride1 = bms.PixelWidth * bytesPerPixel;
byte[] pixels2 = new byte[1080 * 1920 * stride1];
writeableBitmap.WritePixels(new Int32Rect(0, 0, 1080, 1920), pixels2, stride1, 0);
}
catch(Exception e)
{
Console.WriteLine($"catch a exception {e.Message}");
}
}
writeableBitmap 定义:
writeableBitmap = new WriteableBitmap(
//(int)p.win.ActualWidth,//DPI相关
//(int)p.win.ActualHeight,//DPI相关
1080,
1920,
300,
300,
PixelFormats.Bgr32,
null);
解决方案
如果线
BitmapSource bms = (BitmapSource)new ImageSourceConverter().ConvertFrom(frameBody);
成功创建 BitmapSource,frameBody
参数不包含原始像素缓冲区。相反,它是一个编码的图像帧,例如 PNG、JPEG、BMP 或类似的。
目前还不清楚为什么您认为您需要一个 WriteableBitmap。只需分配bms
给 Image 元素的Source
属性:
private void DrawUI(byte[] frameBody)
{
try
{
var bms = (BitmapSource)new ImageSourceConverter().ConvertFrom(frameBody);
image.Source = bms;
}
catch (Exception e)
{
Debug.WriteLine($"catch a exception {e.Message}");
}
}
如果确实需要,您还可以通过创建 BitmapImage 并设置其DecodePixelWidth
或DecodePixelHeight
属性来轻松控制解码位图的大小:
private void DrawUI(byte[] frameBody)
{
try
{
var bitmap = new BitmapImage();
using (var stream = new MemoryStream(frameBody))
{
bitmap.BeginInit();
bitmap.DecodePixelWidth = 1080;
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = stream;
bitmap.EndInit();
}
image.Source = bitmap;
}
catch (Exception e)
{
Debug.WriteLine($"catch a exception {e.Message}");
}
}
推荐阅读
- python - 如何使用 Python 和 MySQL 正确组织数据库调用?
- python - 代码中第一行的意思是“找出奇数位和偶数位之和之间的差异。(最多 100 位)”
- python - 如何从查询集中检索单个值?
- java - log4j2 syslog appender 截断日志消息中的第一个单词
- asp.net-core - 配置粘性会话与转发标头 - Blazor 服务器
- assembly - 纯 Rust 中的原始、非常基本的引导加载程序二进制文件?
- typescript - TS 错误:es2015,类型“数组”
| undefined[]' 必须有一个返回迭代器的 '[Symbol.iterator]()' 方法 - c - 指向具有不同数量参数的函数的函数指针
- javascript - 如何将 vue-gapi 插件与 router.js 和路由器保护一起使用
- json - 如何将所有内容配置到一个或多个配置文件中