@estry

Как растянуть картинку сохранив ее пропорции C#?

Привет. Объясню на примере:
Есть картинка 1200х600, ее нужно вписать в размер 1500х500. Нужно ее растянуть так как будто мышкой взяли за нижний правый край и потянули сохраняя пропорции. То есть на выходе мы будем иметь картинку 1500х500, но нижняя часть будет чуть подрезанная. Мне главное чтобы картинка не была "сплющенной" либо "вытянутой".
Нашел вот такой метод, но он заливает белым фон
static Image ScaleImageMain(Image img)
        {
            int x1 = 200;
            int y1 = 200;
            int x2 = 3;
            int y2 = 3;
            if (img.Width > img.Height)
            {
                x1 = 200;
                y1 = (int)Math.Round((double)img.Height / (img.Width / 200));
                y2 = (int)Math.Round((double)((200 - y1) / 2));

            }
            else
            {
                if (img.Width < img.Height)
                {
                    y1 = 200;
                    x1 = (int)Math.Round((double)img.Width / (img.Height / 200));
                    x2 = (int)Math.Round((double)((200 - x1) / 2));
                }
            }
            img = ScaleImage(img, x1, y1);
            Image dest = new Bitmap(208, 208);
            Graphics gr = Graphics.FromImage(dest);
            // Здесь рисуем рамку.
            Pen blackPen = new Pen(Color.Black, 3);
            float x = 0.0F;
            float y = 0.0F;
            float width = 208.0F;
            float height = 208.0F;
            gr.DrawRectangle(blackPen, x, y, width, height);

            gr.DrawImage(img, x2, y2, img.Width, img.Height);
            dest.Save(@"D:\final1.jpg", ImageFormat.Jpeg);
            return dest;
        }
  • Вопрос задан
  • 467 просмотров
Решения вопроса 1
@estry Автор вопроса
Вот такой код работает как мне надо:
public static System.Drawing.Image FixedSize(Image image, int Width, int Height, bool needToFill)
        {
            #region calculations
            int sourceWidth = image.Width;
            int sourceHeight = image.Height;
            int sourceX = 0;
            int sourceY = 0;
            double destX = 0;
            double destY = 0;

            double nScale = 0;
            double nScaleW = 0;
            double nScaleH = 0;

            nScaleW = ((double)Width / (double)sourceWidth);
            nScaleH = ((double)Height / (double)sourceHeight);
            if (!needToFill)
            {
                nScale = Math.Min(nScaleH, nScaleW);
            }
            else
            {
                nScale = Math.Max(nScaleH, nScaleW);
                destY = (Height - sourceHeight * nScale) / 2;
                destX = (Width - sourceWidth * nScale) / 2;
            }

            if (nScale > 1)
                nScale = 1;

            int destWidth = (int)Math.Round(sourceWidth * nScale);
            int destHeight = (int)Math.Round(sourceHeight * nScale);
            #endregion

            System.Drawing.Bitmap bmPhoto = null;
            try
            {
                bmPhoto = new System.Drawing.Bitmap(destWidth + (int)Math.Round(2 * destX), destHeight + (int)Math.Round(2 * destY));
            }
            catch (Exception ex)
            {
                throw new ApplicationException(string.Format("destWidth:{0}, destX:{1}, destHeight:{2}, desxtY:{3}, Width:{4}, Height:{5}",
                    destWidth, destX, destHeight, destY, Width, Height), ex);
            }
            using (System.Drawing.Graphics grPhoto = System.Drawing.Graphics.FromImage(bmPhoto))
            {
                grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
                grPhoto.CompositingQuality = CompositingQuality.HighQuality;
                grPhoto.SmoothingMode = SmoothingMode.HighQuality;

                Rectangle to = new System.Drawing.Rectangle((int)Math.Round(destX), (int)Math.Round(destY), destWidth, destHeight);
                Rectangle from = new System.Drawing.Rectangle(sourceX, sourceY, sourceWidth, sourceHeight);
                //Console.WriteLine("From: " + from.ToString());
                //Console.WriteLine("To: " + to.ToString());
                grPhoto.DrawImage(image, to, from, System.Drawing.GraphicsUnit.Pixel);
                //bmPhoto.Save(@"D:\final1.jpg");
                return bmPhoto;
            }
        }
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 1
freeExec
@freeExec
Участник OpenStreetMap
Компонент AspectRatio и поиграйтесь там с режимом, скорей всего вам нужен Envelop.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы