Подтвердить что ты не робот

Проверьте ширину и высоту изображения

Я могу отображать изображение в окне изображения без проверки размера файла по следующему коду:

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

Я хочу проверить размер изображения, например, 2 МБ или 4 МБ, прежде чем отображать его в окне изображения. Я также хочу проверить высоту ширины и height.

4b9b3361

Ответ 1

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;

Ответ 2

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

Ответ 3

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