检查图像的宽度和高度

17

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

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

4个回答

44

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;

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

0

我曾经遇到过类似的问题,于是我写了一个方法来检测图片是否为横向或纵向。如果有帮助的话,请参考。

public static bool IsPictureLandscape(string fileName)
{
  try
  {
    Bitmap image = new Bitmap(fileName);
    return image.Width > image.Height;
  }
  catch (Exception)
  {
    return false;
  }
}

0

目前UWP有一个很好的接口来获取图像属性。

        FileOpenPicker openPicker = new FileOpenPicker();
        openPicker.ViewMode = PickerViewMode.Thumbnail;
        openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
        openPicker.FileTypeFilter.Add(".jpg");
        openPicker.FileTypeFilter.Add(".jpeg");
        openPicker.FileTypeFilter.Add(".png");

        StorageFile file = await openPicker.PickSingleFileAsync();
        if (file != null)
        {
            // Application now has read/write access to the picked file
            ImageProperties IP = await file.Properties.GetImagePropertiesAsync();

            double Width = IP.Width;
            double Height = IP.Height;
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接