我在C#vs05窗口上工作。我想通过IDataReader读取图像....在oledb ....我怎么能这样做假设我想从数据库列名学生ID中读取int值然后我以下面的方式编写代码
private IDataReader _reader;
public int GetInt32(String sFieldName)
{
return (_reader[sFieldName]==DBNull.Value)? (Int32) 0 :Convert.ToInt32(_reader[sFieldName]);
}
要保存图像,请使用以下代码
DataTable oTable = new DataTable();
oTable.Columns.Add("BoardImage");
DataRow oRow = oTable.NewRow();
oRow["BoardImage"] = oItem.BoardImage;
SQL= Insert into table oRow["BoardImage"];
Now i want to read image BY Idatareader ......to do that i write bellow code but i get error message "Parameter is not valid."
public Image GetImage(String sFieldName)
{
try
{
//MemoryStream stream = new MemoryStream();
//stream.Write(image, 0, image.Length);
//Bitmap bitmap = new Bitmap(stream);
byte[] imageData = null;
long byteSize = 0;
byteSize = _reader.GetBytes(_reader.GetOrdinal(sFieldName), 0, null, 0, 0); **//May be error occur here**
imageData = new byte[byteSize];
long bytesread = 0;
int curpos = 0, chunkSize = 500;
while (bytesread < byteSize)
{
// chunkSize is an arbitrary application defined value
bytesread += _reader.GetBytes(_reader.GetOrdinal(sFieldName), curpos, imageData, curpos, chunkSize);
curpos += chunkSize;
}
byte[] imgData = imageData;
MemoryStream ms = new MemoryStream(imgData); **//May be error occur here**
Image oImage = Image.FromStream((Stream)ms);
return oImage;
}
catch(Exception ex)
{
throw new Exception("Failed to get Image: " + ex.Message);
}
}
任何人都可以帮助我吗?我的错误在哪里......如何解决这个问题
答案 0 :(得分:4)
尝试类似的事情(确保阅读器处于顺序模式):
using(MemoryStream ms = new MemoryStream()) {
const int BUFFER_SIZE = 1024;
byte[] buffer = new byte[BUFFER_SIZE];
int col = reader.GetOrdinal(fieldName), bytesRead, offset = 0;
while((bytesRead = (int)reader.GetBytes(col,offset,buffer,0,BUFFER_SIZE)) > 0) {
ms.Write(buffer, 0, bytesRead);
offset += bytesRead;
}
ms.Position = 0;
return Image.FromStream(ms);
}
我在原始代码中看到的最大问题是对每次调用GetBytes
时返回的字节数没有太多关注(即假设你有一大块)。