2011-05-18 142 views
8

我能够不通过下面的代码检查文件大小显示在图片框图片:检查图像的宽度和高度

private void button3_Click_1(object sender, EventArgs e) 
{ 
    try 
    { 
     //Getting The Image From The System 
     OpenFileDialog open = new OpenFileDialog(); 
     open.Filter = 
      "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp"; 

     if (open.ShowDialog() == DialogResult.OK) 
     { 
      Bitmap img = new Bitmap(open.FileName); 

      pictureBox2.Image = img; 
     } 
    } 
    catch (Exception) 
    { 
     throw new ApplicationException("Failed loading image"); 
    } 
} 

我要检查,例如图像大小是否在显示在图片框中之前是2MB或4MB。我也想检查图像的宽度高度

回答

28

Bitmap将保存图像的高度和宽度。

使用FileInfoLength属性获取文件大小。

FileInfo file = new FileInfo(open.FileName); 
var sizeInBytes = file.Length; 

Bitmap img = new Bitmap(open.FileName); 

var imageHeight = img.Height; 
var imageWidth = img.Width; 

pictureBox2.Image = img; 
+0

但如何在显示图片框 – bharathi 2011-05-18 12:19:02

+0

图像@bharathi让我先确认你想在内存或大小尺寸在高度和宽度之前检查大小? – Devjosh 2011-05-18 12:21:06

+0

@Devjosh - 他想要两个人。 – Oded 2011-05-18 12:21:51

3
 try 
     { 
      //Getting The Image From The System 
      OpenFileDialog open = new OpenFileDialog(); 
      open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp"; 
      if (open.ShowDialog() == DialogResult.OK) 
      { 
       System.IO.FileInfo file = new System.IO.FileInfo(open.FileName); 
       Bitmap img = new Bitmap(open.FileName); 


       if (img.Width < MAX_WIDTH && 
        img.Height < MAX_HEIGHT && 
        file.Length < MAX_SIZE) 
        pictureBox2.Image = img; 

      } 
     } 
     catch (Exception) 
     { 
      throw new ApplicationException("Failed loading image"); 
     }