如何从数据集中获取图像

本文关键字:集中 获取 图像 数据集 数据 | 更新日期: 2023-09-27 18:21:24

我有包含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();
  }

但图像始终为

在TEMP中,参见System.Byte[]

需要一些帮助,感谢

如何从数据集中获取图像

您的R["PIC"]是一个数组或Bytes。

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

您需要从Byte数组创建一个Image

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); 
    }
}

您需要以顺序访问模式读取数据。下面是一个我用来读取二进制数据的例子。查看的使用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)