Member 13958707 Ответов: 1

Как изменить размер изображения без растягивания/искажения в C#?


Я пытаюсь изменить размер изображения до фиксированного размера, но оно каждый раз искажается.

Что я уже пробовал:

Это мой код.
using System;
using System.Drawing;
using System.Windows.Forms;

namespace ThumbnailImg
{
    public partial class Form1 : Form
    {
        Image imgThumb;

        public Form1()
        {
            InitializeComponent();
        }

        public Image ImgThumb { get => imgThumb; set => imgThumb = value; }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtFileNm.Text = openFileDialog1.FileName;
                MessageBox.Show("Image Uploaded");
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            

            try
            {
                Image image = null;
                // Check if textbox has a value
                if (txtFileNm.Text != String.Empty)
                    image = Image.FromFile(txtFileNm.Text);
                // Check if image exists
                if (image != null)
                {
                    ImgThumb = image.GetThumbnailImage(100, 100, null, new IntPtr());
                    this.Refresh();
                    ImgThumb.Save("C:\\Users\\Acer\\Pictures\\Camera Roll\\thumbnail.jpg");
                    MessageBox.Show("Image saved successfully");
                }
            }
            catch
            {
                MessageBox.Show("An error occured");
            }
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            if (ImgThumb != null)
                e.Graphics.DrawImage(ImgThumb, 30, 20, ImgThumb.Width, ImgThumb.Height);
        }
    }
}

1 Ответов

Рейтинг:
7

Richard MacCutchan

Вы должны сохранить соотношение сторон одинаковым при регулировке размера, вы не можете просто использовать произвольные значения для ширины и высоты.

Я нашел это в http://blogs.techrepublic.com/howdoi/?p=124[^]

The key to keeping the correct aspect ratio while resizing an image is the algorithm used to calculate the ratio, viz.

NewHeight = GivenWidth * (OriginalHeight / OriginalWidth)

or

NewWidth = GivenHeight * (OriginalWidth / OriginalHeight)

This calculation assumes that the "Given..." is the dimension the image should be resized to. Once we know this, we can multiply it by the original image’s aspect, and that will give us the other side's value we need. So, assuming the original image has a width of 1000 and a height of 1600 and we want it to be resized to a width of 500:

First find the aspect: (1600 / 1000) = aspect of 1.6
Now multiply the aspect by the desired new width: 1.6 * 500
The result of that multiplication is 800, which is what our height should be

In other words:
800 = 500 * (1600 / 1000)

So the resulting image would have a height of 800 and a width of 500.


Member 13958707

Спасибо!! Это очень помогло