Skip to main content
 首页 » 编程设计

c#之在 Core 2.1 中将 byte[] 转换为 Bitmap

2024年01月29日33unruledboy

我有一个在 .Net 4.6.2 中运行良好的项目,它大量使用了将 byte[] 转换为位图。

public static Bitmap ByteArrayToImage(byte[] source) 
    { 
        TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap)); 
        return (Bitmap)tc.ConvertFrom(source); 
    } 

但是,我已经将项目升级到 .Net Core 2.1,这不再有效。我读过,有几个人遇到了问题,但正在努力寻找解决办法。

TypeConverter cannot convert from System.Byte[]

2.1有没有办法实现这种转换? 看起来像 https://github.com/SixLabors/ImageSharp可能有效,但是当我在 Nuget 中搜索它时,我没有得到任何结果。

请您参考如下方法:

您需要将字节放入MemoryStream

public static Bitmap ByteArrayToImage(byte[] source) 
{ 
    using (var ms = new MemoryStream(source)) 
    { 
        return new Bitmap(ms); 
    } 
} 

上面的代码将使用Bitmap(Stream stream)构造函数。