我正在使用具有FromBinary方法的图像组件。想知道如何将输入流转换为字节数组
HttpPostedFile file = context.Request.Files[0];
byte[] buffer = new byte[file.ContentLength];
file.InputStream.Read(buffer, 0, file.ContentLength);
ImageElement image = ImageElement.FromBinary(byteArray);
答案 0 :(得分:272)
使用BinaryReader对象从流中返回字节数组,如:
byte[] fileData = null;
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}
答案 1 :(得分:22)
BinaryReader b = new BinaryReader(file.InputStream);
byte[] binData = b.ReadBytes(file.InputStream.Length);
第2行应替换为
byte[] binData = b.ReadBytes(file.ContentLength);
答案 2 :(得分:11)
如果您的文件InputStream.Position设置为流的末尾,则无效。 我的其他内容:
Stream stream = file.InputStream;
stream.Position = 0;
答案 3 :(得分:3)
在你的问题中,buffer和byteArray似乎都是byte []。所以:
ImageElement image = ImageElement.FromBinary(buffer);
答案 4 :(得分:2)
,必须将stream.position重置为0;然后 它工作正常。
答案 5 :(得分:2)
对于使用网页v2使用的图像 WebImage Class
var webImage = new System.Web.Helpers.WebImage(Request.Files[0].InputStream);
byte[] imgByteArray = webImage.GetBytes();