类型转换器,用于将字节 [] 转换为位图

本文关键字:转换 位图 字节 类型转换 转换器 用于 类型 | 更新日期: 2023-09-27 18:36:13

>我有这个:

byte[] ar = new byte[ArrayAnsammlung[DurchLaeufer].Length];
ArrayAnsammlung[DurchLaeufer].CopyTo(ar, 0);
TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));
try
{
    bild = (Bitmap)tc.ConvertFrom(ar);
}
catch (Exception ddd)
{
    Console.WriteLine(ddd.ToString());
}

ar包含位图数据,即蓝-绿-红-阿尔法-蓝....

我正在尝试将其转换为位图图片。这是控制台显示的内容:

A first chance exception of type 'System.ArgumentException' occurred in System.Drawing.dll
System.ArgumentException: Invalid Parameter.
   at System.Drawing.Image.FromStream(Stream stream, Boolean useEmbeddedColorManagement, Boolean validateImageData)
   at System.Drawing.ImageConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
   at System.ComponentModel.TypeConverter.ConvertFrom(Object value)
   at SK.MainWindow.thread() in MainWindow.xaml.cs:Zeile 523.

如何解决此问题?

类型转换器,用于将字节 [] 转换为位图

试试这个:

public static Bitmap BytesToBitmap(byte[] byteArray)
{
    using (MemoryStream ms = new MemoryStream(byteArray))
    {
        Bitmap img = (Bitmap)Image.FromStream(ms);
        return img;
    }
}

我不确定为什么TypeConverter不起作用,但您可以使用 Bitmap 类的 Stream 构造函数轻松实现这一点:

var memoryStream = new MemoryStream(ar)
var bild = new Bitmap(memoryStream);

请注意,根据 MSDN,memoryStream必须在对象的生存期内保持活动状态。