Skip to main content
 首页 » 编程设计

C# 可移植类库之使用图像

2024年08月06日25kuangbin

我正在编写一个库,它使用网络 API 下载图像。我需要这个库可以在许多平台上使用,所以我选择了一个可移植类库。通常我会使用 System.Drawing 中的 Bitmap 类型将下载的图像存储在内存中,然后传递给方法等。

但是,由于 PCL 的平台独立方式,PCL 无法访问此类。因此,我正在考虑将图像简单地下载到 byte[] 数组中,然后由使用该库的应用程序使用。使用字节数组来保存下载的图片会不会有什么潜在的问题?

请您参考如下方法:

我认为使用 byte[] 存储图像不会有任何重大的潜在问题。

我能想到的唯一一件事是将图像转换为 byte[] 并返回的潜在开销。

此外,除了在 byte[] 中,我想不出任何更好的方法来存储图像。

此外,您可以为包含 byte[] 的数据类编写一个扩展方法,以在您可以使用它的地方返回 Bitmap。

public static class DataClassExtensions 
{ 
     public static BitmapImage GetImage(this DataClass data) 
     { 
         if(data == null || data.ImageArray == null) return null; 
 
         using (var ms = new System.IO.MemoryStream(data.ImageArray)) 
         { 
              Bitmap image = (Bitmap)Image.FromStream(ms); 
              return image; 
         } 
     } 
} 
 
public class DataClass 
{ 
     public byte[] ImageArray { get; set; } 
}