Extracting an image with 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;

      

The code creates a problem when the line "Image oImage = Image.FromStream((Stream)ms);"

..... This line displays a message "Parameter is not valid"

....... Why is this happening? Help me. I want to get an image from a database .... I am working in a C # vs05 window ..... Can anyone help me? byte [] contains the value. Everything works well, just the problem occurs when this line is executed.

0


a source to share


2 answers


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



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

return null;

      

+1


a source


I cannot detect any errors in this code (other than that the MemoryStream was not deleted, and that there is no need to pass it in Stream

when passing it to a method Image.FromStream

, but that shouldn't cause your error). I would do the following to try and find the error:



  • Write the byte data to a file and try to open the image in a graphics program (to make sure the byte data actually represents a valid image). I guess this will fail.
  • Check the code that writes data to the database (maybe do the same trick as in the previous point, write it to a file and try to open the file)
0


a source







All Articles