检查图像的宽度和高度

本文关键字:高度 图像 检查 | 更新日期: 2023-09-27 17:57:04

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

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

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

我遇到了类似的问题,我编写了一种方法来检测图片是否是横向的。如果它能帮助你。

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