C#位图图像,字节数组和流!

ias*_*ons 1 c# arrays byte image stream

我有一个函数将文件提取到字节数组(数据).

        int contentLength = postedFile.ContentLength;
        byte[] data = new byte[contentLength];
        postedFile.InputStream.Read(data, 0, contentLength);
Run Code Online (Sandbox Code Playgroud)

后来我使用这个字节数组来构造一个System.Drawing.Image对象(其中data是字节数组)

       MemoryStream ms = new MemoryStream(data);
       Image bitmap = Image.FromStream(ms);
Run Code Online (Sandbox Code Playgroud)

我得到以下异常"ArgumentException:参数无效."

原始发布的文件包含500k jpeg图像...

任何想法为什么这不起作用?

注意:我向你保证我有一个有效的理由转换为字节数组然后转换为内存流!!

Guf*_*ffa 5

这很可能是因为您没有将所有文件数据都放入字节数组中.Read方法不必返回您请求的字节数,它返回实际放入数组的字节数.你必须循环,直到你获得所有数据:

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

从流中读取时,这是一个常见的错误.我已经多次看到这个问题了.

编辑:
检查流的早期结束,正如马修建议的那样,代码将是:

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;
}
Run Code Online (Sandbox Code Playgroud)

  • @ListenToRick:你已经在for语句中添加了一个额外的p ++,它不应该存在.这将在您读取的数据块之间产生一个字节的间隔. (3认同)