C#位图图像,字节数组和流! [英] C# bitmap images, byte arrays and streams!

查看:192
本文介绍了C#位图图像,字节数组和流!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个提取文件转换成字节数组功能(数据)。

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

        int contentLength = postedFile.ContentLength;
        byte[] data = new byte[contentLength];
        postedFile.InputStream.Read(data, 0, contentLength);

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

Later I use this byte array to construct an System.Drawing.Image object (where data is the byte array)

       MemoryStream ms = new MemoryStream(data);
       Image bitmap = Image.FromStream(ms);

我得到下面的异常的ArgumentException:参数是无效的。

I get the following exception "ArgumentException: Parameter is not valid."

的原贴文件包含一个500K JPEG图像...

The original posted file contained a 500k jpeg image...

任何想法,为什么这个心不是工作吗?

Any ideas why this isnt working?

请注意:我向你保证,我有一个有效的理由转换为字节数组,然后到一个MemoryStream!

Note: I assure you I have a valid reason for converting to a byte array and then to a memorystream!!

推荐答案

这是最有可能是因为你没有所有的文件数据进入字节数组。读取方法不具有如您请求返回尽可能多的字节,并且它返回实际把阵列中的字节数。你必须循环,直到你得到的所有数据:

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.

编辑:

随着检查流的早日结束,马修建议,在code将是:


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;
}

这篇关于C#位图图像,字节数组和流!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆