byte[] bytes = BitmapToByteArray(bmp); 可以指定图片格式嘛System.Drawing.Imaging.ImageFormat.Jpeg
时间: 2024-02-09 19:10:04 浏览: 22
是的,可以指定图片格式。在调用 `Bitmap.Save()` 方法时,可以传入一个 `System.Drawing.Imaging.ImageFormat` 枚举值,来指定保存的图片格式。该枚举包含了几种常见的图片格式,如 JPEG、PNG、BMP 等。
以下是示例代码:
```csharp
// 将 Bitmap 对象转换成指定格式的 byte[] 数组
public byte[] BitmapToByteArray(Bitmap bmp, ImageFormat format)
{
using (MemoryStream stream = new MemoryStream())
{
bmp.Save(stream, format);
return stream.ToArray();
}
}
```
使用示例:
```csharp
byte[] bytes = BitmapToByteArray(bmp, ImageFormat.Png); // 保存为 PNG 格式的字节数组
```
这样,就可以将 `Bitmap` 对象保存为指定格式的字节数组了。
相关问题
system.windows.media.imaging.bitmapimage system.drawing.bitmap 互转
要将 `System.Windows.Media.Imaging.BitmapImage` 和 `System.Drawing.Bitmap` 互相转换,可以使用以下代码:
```csharp
// 将 BitmapImage 转换为 Bitmap
public static Bitmap BitmapImage2Bitmap(BitmapImage bitmapImage)
{
using (MemoryStream outStream = new MemoryStream())
{
BitmapEncoder encoder = new BmpBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
encoder.Save(outStream);
Bitmap bitmap = new Bitmap(outStream);
return new Bitmap(bitmap);
}
}
// 将 Bitmap 转换为 BitmapImage
public static BitmapImage Bitmap2BitmapImage(Bitmap bitmap)
{
using (MemoryStream outStream = new MemoryStream())
{
bitmap.Save(outStream, ImageFormat.Bmp);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = new MemoryStream(outStream.ToArray());
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
return bitmapImage;
}
}
```
需要注意的是,这两个类所在的命名空间是不同的,因此要先引入相应的命名空间:
```csharp
using System.Windows.Media.Imaging;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
```
WPF中如何将System.Drawing.Image复制给Image控件
在 WPF 中,可以使用 `System.Windows.Media.Imaging.BitmapImage` 类将 `System.Drawing.Image` 对象转换为 `System.Windows.Controls.Image` 控件可以使用的 `ImageSource` 对象。以下是一个示例代码:
```csharp
using System.Drawing;
using System.Windows.Media.Imaging;
// 将 System.Drawing.Image 对象复制给 Image 控件
public static void CopyImageToWpf(Image image, System.Windows.Controls.Image wpfImage)
{
// 将 System.Drawing.Image 对象转换为 BitmapImage 对象
Bitmap bitmap = new Bitmap(image);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
MemoryStream memoryStream = new MemoryStream();
bitmap.Save(memoryStream, ImageFormat.Bmp);
memoryStream.Seek(0, SeekOrigin.Begin);
bitmapImage.StreamSource = memoryStream;
bitmapImage.EndInit();
// 将 BitmapImage 对象设置为 Image 控件的源
wpfImage.Source = bitmapImage;
}
```
在上面的代码中,我们首先将 `System.Drawing.Image` 对象转换为 `System.Windows.Media.Imaging.BitmapImage` 对象,然后将其设置为 `System.Windows.Controls.Image` 控件的源。需要注意的是,在将 `System.Drawing.Image` 转换为 `BitmapImage` 对象时,我们需要将其保存为 `MemoryStream` 对象,并将其设置为 `BitmapImage.StreamSource` 属性的值。