2

这是这个问题的后续:如何将 SQL Server BLOB 字符串转换为 System.Drawing.Image?

背景

我将使用 c# 从 csv 文件中导入有关用户的信息以及他们的照片。我使用的专有 SDK 要求照片是 System.Drawing.Image

以下是 csv 文件的示例:

surname firstname   photo                       
Blogs    Joe        0xFFD8FFE000104A46494600010101005F005F0000FFDB0043000D090A

我使用在上一个问题的答案中找到的代码(如何将 SQL Server BLOB 字符串转换为 System.Drawing.Image?)将由十六进制字符串表示的 BLOB 转换为字节数组,然后转换为系统.绘图.图像。

这是我用来将 BLOB 的十六进制字符串转换为字节数组的代码(来自我之前的问题)。这个原则有效。

  strPhoto = csvuser.photo; // The string that represents the BLOB

  //remove first 2 chars (the '0x')
  strPhoto = strPhoto.Remove(0, 2);

  //convert hex-string to bytes:
  int NumberChars = strPhoto.Length/2;
  byte[] bytes = new byte[NumberChars];
  using (StringReader sr = new StringReader(strPhoto)){
        for (int i = 0; i < NumberChars; i++)
           bytes[i] = Convert.ToByte(new string(new char[2]{(char)sr.Read(), (char)sr.Read()}), 16);
  }

  // Then we create a memory stream that holds the image
  MemoryStream photostream = new MemoryStream( bytes );

  // Then we can create a System.Drawing.Image by using the Memory stream
  var photo = Image.FromStream(photostream);

然而,一些更高分辨率的图像被阈值化,因此照片的下半部分是黑色的,带有一些可预测的白点图案,而上半部分是预期的。

正确导入的照片是

>=640x480

而那些不是

<640x480

在尺寸方面。所有位深度均为 24。这是我观察到的,但不确定是否相关。原始图像是 24 位的,在我看来,转换为字节数组会创建一个较低位的“图像”,因此照片的一半是黑色的,带有可预测的白点图案。

问题

如何将十六进制字符串转换为字节数组以避免意外阈值?

4

0 回答 0