C# bitmap images, byte arrays and streams!

后端 未结 5 658
醉梦人生
醉梦人生 2021-01-25 17:12

I have a function which extracts a file into a byte array (data).

        int contentLength = postedFile.ContentLength;
        byte[] data = new byte[contentLen         


        
相关标签:
5条回答
  • 2021-01-25 17:13

    I have had problems loading images in .NET that were openable by more robust image libraries. It's possible that the specific jpeg image you have is not supported by .NET. jpeg files are not just one type of encoding, there's a variety of possible compression schemes allowed.

    You could try it with another image that you know is in a supported format.

    0 讨论(0)
  • 2021-01-25 17:22

    That's most likely because you didn't get all the file data into the byte array. The Read method doesn't have to return as many bytes as you request, and it returns the number of bytes actually put in the array. You have to loop until you have gotten all the data:

    int contentLength = postedFile.ContentLength;
    byte[] data = new byte[contentLength];
    for (int pos = 0; pos < contentLength; ) {
       pos += postedFile.InputStream.Read(data, pos, contentLength - pos);
    }
    

    This is a common mistake when reading from a stream. I have seen this problem a lot of times.

    Edit:
    With the check for an early end of stream, as Matthew suggested, the code would be:

    int contentLength = postedFile.ContentLength;
    byte[] data = new byte[contentLength];
    for (int pos = 0; pos < contentLength; ) {
       int len = postedFile.InputStream.Read(data, pos, contentLength - pos);
       if (len == 0) {
          throw new ApplicationException("Upload aborted.");
       }
       pos += len;
    }
    
    0 讨论(0)
  • 2021-01-25 17:26

    You're not checking the return value of postedFile.InputStream.Read. It is not at all guaranteed to fill the array on the first call. That will leave a corrupt JPEG in data (0's instead of file content).

    0 讨论(0)
  • 2021-01-25 17:28

    Have you checked the return value from the Read() call to verify that is actually reading all of the content? Perhaps Read() is only returning a portion of the stream, requiring you to loop the Read() call until all of the bytes are consumed.

    0 讨论(0)
  • 2021-01-25 17:40

    Any reason why you don't simply do this:

    Image bitmap = Image.FromStream(postedFile.InputStream);
    
    0 讨论(0)
提交回复
热议问题