简体   繁体   中英

Image Retrieve using c#

byte[] imageData = null;
long byteSize = 0;
byteSize = _reader.GetBytes(_reader.GetOrdinal(sFieldName), 0, null, 0, 0);

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);
Image oImage = Image.FromStream((Stream)ms);
return oImage;

Code creates problem when "Image oImage = Image.FromStream((Stream)ms);" line executes.....This line shows "Parameter is not valid" message .......Why it occurs? Help me. I want to retrieve image from database ....I work on C# window vs05 .....Can any one help me? byte[] contain value. All works well, just problem occurs when this line executes.

A simple if statement should solve your problem before creating the memory stream

if (imageData.Length != 0)
{
  MemoryStream ms = new MemoryStream(imageData);
  Image oImage = Image.FromStream((Stream)ms);
  return oImage;
}

return null;

I can't really spot any errors in this code (other than the MemoryStream not being disposed, and that it's not necessary to cast it to Stream when passing it to the Image.FromStream method; but those should not cause your error). I would do the following in order to try to find the error:

  • Write the byte data to a file and try to open the image in a graphics program (to verify that the byte data does indeed represent a valid image). My guess is that this would fail.
  • Check the code that writes the data to the database (perhaps perform the same trick as in the previous point; write it to a file and try to open the file)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM