2011-05-18 19 views
8

soy capaz de mostrar la imagen en el cuadro de imagen sin comprobar el tamaño del archivo en el siguiente código:Compruebe el ancho y la altura de una imagen

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

Quiero comprobar el tamaño de la imagen, por ejemplo, si se es 2MB o 4MB antes de mostrar en el cuadro de imagen. También quiero comprobar el ancho y altura de la imagen.

Respuesta

28

El Bitmap mantendrá el alto y el ancho de la imagen.

Utilice la propiedad FileInfoLength para obtener el tamaño del archivo.

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

Pero cómo comprobar el tamaño antes de mostrar la imagen en el cuadro de imagen – bharathi

+0

@bharathi les confirmo que primero es lo que quiere el tamaño de la memoria o el tamaño en altura y anchura? – Devjosh

+0

@Devjosh - él quiere los dos. – Oded

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