检查图像的宽度和高度

我可以在图片框中显示图片,而无需通过以下代码检查文件大小:

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 。 我还想检查图像的宽度高度

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

使用FileInfo Length属性获取文件大小。

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