如何从DataSet获取图像

时间:2015-11-10 11:29:15

标签: c# winforms windows-mobile

我有包含Image的DataSet。

我需要将此图像保存到文件。

我试试这个:

SQL = ItemCode,PIC from ROW;
dsView = new DataSet();
adp = new SqlCeDataAdapter(SQL, Conn);
adp.Fill(dsView, "ROW");
adp.Dispose();
foreach (DataRow R in dsROW.Tables[0].Rows)
{
 ItemCode = R["ItemCode"].ToString().Trim() ;
 TEMP = R["PIC"].ToString().Trim();  
 Image image = R["PIC"] as Image;
 if(image != null)
 {
   MemoryStream ms = new MemoryStream();
   image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
   byte[] imagedata = ms.ToArray();
  }

但是图片始终 null

在TEMP中我看到 System.Byte []

需要一些帮助,谢谢

2 个答案:

答案 0 :(得分:0)

您的R["PIC"]是数组或字节。

首先,您尝试对其应用ToString(),然后只需获取System.Byte[] 然后,您尝试将其强制转换为ImageByte[]如何施放Image

您需要从Image数组创建Byte

dsView = new DataSet();
adp = new SqlCeDataAdapter(SQL, Conn);
adp.Fill(dsView, "ROW");
adp.Dispose();
foreach (DataRow R in dsROW.Tables[0].Rows)
{
    ItemCode = R["ItemCode"].ToString().Trim();

    using (var ms = new MemoryStream(R["PIC"]))
    {
        Image image = Image.FromStream(ms);
        image.Save($"C:\\Output\\YourCustomPath\\{ItemCode}.jpeg", ImageFormat.Jpeg); 
    }
}

答案 1 :(得分:0)

您需要以顺序访问模式读取数据。这是我用来读取二进制数据的例子。见使用     SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess);

片段:

string sql = "Select file_data from utils where util_id="+uID.ToString()+";";
SqlCommand cmd = new SqlCommand(sql, database._sqlConnection);
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess); // CommandBehavior.SequentialAccess: read columns in order and every column only once!
int columnNr = 0;
byte[] filedata = null;
try
{
  while (rdr.Read())
  {
//load the binary data
if (rdr.IsDBNull(columnNr)) //is there any binary data? //LAST COLUMN!!!!!
filedata = null;
else
{
  //read binary data
  int bufferSize = 100; // Size of the BLOB buffer.
  byte[] outbyte = new byte[bufferSize]; // The BLOB byte[] buffer to be filled by GetBytes.
  long retval; // The bytes returned from GetBytes.
  long startIndex = 0; // The starting position in the BLOB output.
  MemoryStream ms = new MemoryStream();
  BinaryWriter bw = new BinaryWriter(ms);
  // Reset the starting byte for the new BLOB.
  startIndex = 0;
  // Read the bytes into outbyte[] and retain the number of bytes returned.
  retval = rdr.GetBytes(columnNr, startIndex, outbyte, 0, bufferSize);
  // Continue reading and writing while there are bytes beyond the size of the buffer.
  while (retval >0) //== bufferSize)
  {
    bw.Write(outbyte);
    bw.Flush();
    // Reposition the start index to the end of the last buffer and fill the buffer.
    startIndex += bufferSize;
    retval = rdr.GetBytes(columnNr, startIndex, outbyte, 0, bufferSize);
  }
  bw.Close();
  filedata = ms.ToArray();
  ms.Close();
}
  }
}
catch (SqlException ex)