2013-05-20 11 views
11

を使用して画像サイズ(幅x高)を取得することができます私は、アップロードされたファイルを読み込むために使用していますが、私ではなく、画像のサイズを取得する必要がありますが、わからないどのようなコード私はは、どのように私はこのコードを持っているストリーム

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

を使用することができます私はファイルを取得することはできますが、イメージ(幅とサイズ)を確認する方法はありますか?

答えて

32

まず、あなたが画像を記述する必要があります:

System.Drawing.Image image = System.Drawing.Image.FromStream (new System.IO.MemoryStream(byteArrayHere)); 

、その後、あなたが持っている:

image.Height.ToString(); 

image.Width.ToString(); 

注:チェックを追加したいかもしれませんがアップロードされた画像であることを確認しますか?

+0

いただきましたバイト配列の先生:( – Mathematics

+0

うわー... OK:バイト[] < - バイト配列 - あなたの場合: ' fileContents' – Rob

+11

ねえ、それを 'using'節に入れてください! –

4
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(); 
} 
1

イメージをバッファーに読み込みます(読み込みストリームまたはバイト[]があります。これは、イメージがあればディメンションがあるためです)。

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; 
関連する問題