我有这个代码,我用来读取上传的文件,但我需要得到图像的大小,而不是不确定什么代码可以使用
HttpFileCollection collection = _context.Request.Files;
for (int i = 0; i < collection.Count; i++)
{
HttpPostedFile postedFile = collection[i];
Stream fileStream = postedFile.InputStream;
fileStream.Position = 0;
byte[] fileContents = new byte[postedFile.ContentLength];
fileStream.Read(fileContents, 0, postedFile.ContentLength);
我可以得到正确的文件,但如何检查它的图像(宽度和大小)先生?
首先你必须写图像:
System.Drawing.Image image = System.Drawing.Image.FromStream (new System.IO.MemoryStream(byteArrayHere));
后面是:
image.Height.ToString();
和
image.Width.ToString();
注意:你可能想要添加一个检查,以确保它是一个图片上传?
HttpPostedFile file = null;
file = Request.Files[0]
if (file != null && file.ContentLength > 0)
{
System.IO.Stream fileStream = file.InputStream;
fileStream.Position = 0;
byte[] fileContents = new byte[file.ContentLength];
fileStream.Read(fileContents, 0, file.ContentLength);
System.Drawing.Image image = System.Drawing.Image.FromStream(new System.IO.MemoryStream(fileContents));
image.Height.ToString();
}
将图像读入缓冲区(您可以读取流或字节[],因为如果您有图像,则无论如何都会有尺寸)
public Size GetSize(byte[] bytes)
{
using (var stream = new MemoryStream(bytes))
{
var image = System.Drawing.Image.FromStream(stream);
return image.Size;
}
}
你可以继续获取图像尺寸:
var size = GetSize(bytes);
var width = size.Width;
var height = size.Height;