WPF中,通过BitmapImage从文件中读入文件1.bmp,并将读入后的bitmapImage转换为byte[]类型输出,同时输出图宽高
时间: 2024-10-21 09:17:48 浏览: 49
在WPF中,如果你想从文件`file1.bmp`读取图像数据并将其转换为`byte[]`,同时获取图像的宽度和高度,你可以按照以下步骤操作:
1. 首先,创建一个`BitmapImage`对象来加载图像:
```csharp
BitmapImage bitmapImage = new BitmapImage(new Uri("file1.bmp", UriKind.RelativeOrAbsolute));
```
这里假设`file1.bmp`是在应用程序资源目录下,如果不是,需要提供完整的路径。
2. 使用`GetPixelWidth()`和`GetPixelHeight()`方法获取图像的实际宽度和高度:
```csharp
int width = bitmapImage.PixelWidth;
int height = bitmapImage.PixelHeight;
```
3. 转换`BitmapImage`到`byte[]`数组。由于`BitmapImage`本身并不直接提供这样的功能,你需要创建一个临时`WriteableBitmap`,然后保存为新的`byte[]`:
```csharp
using (var stream = new MemoryStream())
{
WriteableBitmap wbmp = new WriteableBitmap(bitmapImage.Width, bitmapImage.Height);
wbmp.CopyPixels(bitmapImage, PixelFormats.Bgra32, 0, 0);
wbmp.SaveJpg(stream); // 注意这里使用SaveJpg而不是SavePng,因为WriteableBitmap不支持原生的BMP格式
byte[] imageData = stream.ToArray();
}
```
请注意,上述代码使用了`SaveJpg`方法来保存到`byte[]`,这是因为`WriteableBitmap`默认不支持BMP格式的保存,通常会使用`jpg`或者其他更广泛的格式。
阅读全文
相关推荐















