gpt4 book ai didi

c# - 如何通过 IDataReader 读取图像

转载 作者:太空宇宙 更新时间:2023-11-03 22:27:19 25 4
gpt4 key购买 nike

我在窗口 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);
}
}

任何人都可以帮助我吗?我的错误在哪里.....如何解决这个问题

最佳答案

尝试类似的操作(确保阅读器处于顺序模式):

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 返回的字节数(即假设您有一个完整的 block )。

关于c# - 如何通过 IDataReader 读取图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/891617/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com