Как изменить размер bitmap c

I want to have smaller size at image saved. How can I resize it? I use this code for redering the image: Size size = new Size(surface.Width, surface.Height); surface.Measure(size); surface.Arrang...

I want to have smaller size at image saved.
How can I resize it?
I use this code for redering the image:

Size size = new Size(surface.Width, surface.Height);
surface.Measure(size);
surface.Arrange(new Rect(size));
// Create a render bitmap and push the surface to it
RenderTargetBitmap renderBitmap =
    new RenderTargetBitmap(
        (int)size.Width,
        (int)size.Height, 96d, 96d,
        PixelFormats.Default);
renderBitmap.Render(surface);

BmpBitmapEncoder encoder = new BmpBitmapEncoder();
// push the rendered bitmap to it
encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
// save the data to the stream
encoder.Save(outStream);

Khanzor's user avatar

Khanzor

4,7502 gold badges24 silver badges40 bronze badges

asked May 31, 2012 at 18:41

Ionică Bizău's user avatar

Ionică BizăuIonică Bizău

106k86 gold badges282 silver badges464 bronze badges

public static Bitmap ResizeImage(Bitmap imgToResize, Size size)
{
    try
    {
        Bitmap b = new Bitmap(size.Width, size.Height);
        using (Graphics g = Graphics.FromImage((Image)b))
        {
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            g.DrawImage(imgToResize, 0, 0, size.Width, size.Height);
        }
        return b;
    }
    catch 
    { 
        Console.WriteLine("Bitmap could not be resized");
        return imgToResize; 
    }
}

Max von Hippel's user avatar

answered May 31, 2012 at 18:46

Kashif's user avatar

2

The shortest way to resize a Bitmap is to pass it to a Bitmap-constructor together with the desired size (or width and height):

bitmap = new Bitmap(bitmap, width, height);

answered Apr 13, 2016 at 14:58

Breeze's user avatar

BreezeBreeze

1,9802 gold badges34 silver badges41 bronze badges

3

Does your «surface» visual have scaling capability? You can wrap it in a Viewbox if not, then render the Viewbox at the size you want.

When you call Measure and Arrange on the surface, you should provide the size you want the bitmap to be.

To use the Viewbox, change your code to something like the following:

Viewbox viewbox = new Viewbox();
Size desiredSize = new Size(surface.Width / 2, surface.Height / 2);

viewbox.Child = surface;
viewbox.Measure(desiredSize);
viewbox.Arrange(new Rect(desiredSize));

RenderTargetBitmap renderBitmap =
    new RenderTargetBitmap(
    (int)desiredSize.Width,
    (int)desiredSize.Height, 96d, 96d,
    PixelFormats.Default);
renderBitmap.Render(viewbox);

answered May 31, 2012 at 18:52

Trevor Elliott's user avatar

Trevor ElliottTrevor Elliott

11.2k11 gold badges60 silver badges102 bronze badges

0

  • Remove From My Forums
  • Вопрос

  • конструктором Bitmap(int,int) создан рисунок

    подскажите  как изменить его размер? свойств подходящих не нашел

Ответы

  • Добрый день.

    Вот так:

    Bitmap big = new Bitmap(100, 100);
    Bitmap small = new Bitmap(Image.FromHbitmap(big.GetHbitmap()), 50, 50);

    • Предложено в качестве ответа

      3 сентября 2014 г. 23:12

    • Помечено в качестве ответа
      Алексей ЛосевEditor
      30 сентября 2014 г. 12:26

  • Если размер изменяется, это уже другой Bitmap. Поймите, нельзя «по месту» изменить размер изображения. На него много чего «завязано», в частности, массив пикселей. Так что, не нужно огород
    городить, «тот же объект» использовать не получится. Придумайте другое решение.


    Если сообщение помогло Вам, пожалуйста, не забудьте отметить его как ответ данной темы. Удачи в программировании!

    • Изменено
      kosuke904
      3 сентября 2014 г. 19:59
    • Предложено в качестве ответа
      Maxim Shusharin
      3 сентября 2014 г. 23:12
    • Помечено в качестве ответа
      Алексей ЛосевEditor
      30 сентября 2014 г. 12:26

Here you can find also add watermark codes in this class :

public class ImageProcessor
    {
        public Bitmap Resize(Bitmap image, int newWidth, int newHeight, string message)
        {
            try
            {
                Bitmap newImage = new Bitmap(newWidth, Calculations(image.Width, image.Height, newWidth));

                using (Graphics gr = Graphics.FromImage(newImage))
                {
                    gr.SmoothingMode = SmoothingMode.AntiAlias;
                    gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    gr.DrawImage(image, new Rectangle(0, 0, newImage.Width, newImage.Height));

                    var myBrush = new SolidBrush(Color.FromArgb(70, 205, 205, 205));

                    double diagonal = Math.Sqrt(newImage.Width * newImage.Width + newImage.Height * newImage.Height);

                    Rectangle containerBox = new Rectangle();

                    containerBox.X = (int)(diagonal / 10);
                    float messageLength = (float)(diagonal / message.Length * 1);
                    containerBox.Y = -(int)(messageLength / 1.6);

                    Font stringFont = new Font("verdana", messageLength);

                    StringFormat sf = new StringFormat();

                    float slope = (float)(Math.Atan2(newImage.Height, newImage.Width) * 180 / Math.PI);

                    gr.RotateTransform(slope);
                    gr.DrawString(message, stringFont, myBrush, containerBox, sf);
                    return newImage;
                }
            }
            catch (Exception exc)
            {
                throw exc;
            }
        }

        public int Calculations(decimal w1, decimal h1, int newWidth)
        {
            decimal height = 0;
            decimal ratio = 0;


            if (newWidth < w1)
            {
                ratio = w1 / newWidth;
                height = h1 / ratio;

                return height.To<int>();
            }

            if (w1 < newWidth)
            {
                ratio = newWidth / w1;
                height = h1 * ratio;
                return height.To<int>();
            }

            return height.To<int>();
        }

    }

Here you can find also add watermark codes in this class :

public class ImageProcessor
    {
        public Bitmap Resize(Bitmap image, int newWidth, int newHeight, string message)
        {
            try
            {
                Bitmap newImage = new Bitmap(newWidth, Calculations(image.Width, image.Height, newWidth));

                using (Graphics gr = Graphics.FromImage(newImage))
                {
                    gr.SmoothingMode = SmoothingMode.AntiAlias;
                    gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    gr.DrawImage(image, new Rectangle(0, 0, newImage.Width, newImage.Height));

                    var myBrush = new SolidBrush(Color.FromArgb(70, 205, 205, 205));

                    double diagonal = Math.Sqrt(newImage.Width * newImage.Width + newImage.Height * newImage.Height);

                    Rectangle containerBox = new Rectangle();

                    containerBox.X = (int)(diagonal / 10);
                    float messageLength = (float)(diagonal / message.Length * 1);
                    containerBox.Y = -(int)(messageLength / 1.6);

                    Font stringFont = new Font("verdana", messageLength);

                    StringFormat sf = new StringFormat();

                    float slope = (float)(Math.Atan2(newImage.Height, newImage.Width) * 180 / Math.PI);

                    gr.RotateTransform(slope);
                    gr.DrawString(message, stringFont, myBrush, containerBox, sf);
                    return newImage;
                }
            }
            catch (Exception exc)
            {
                throw exc;
            }
        }

        public int Calculations(decimal w1, decimal h1, int newWidth)
        {
            decimal height = 0;
            decimal ratio = 0;


            if (newWidth < w1)
            {
                ratio = w1 / newWidth;
                height = h1 / ratio;

                return height.To<int>();
            }

            if (w1 < newWidth)
            {
                ratio = newWidth / w1;
                height = h1 * ratio;
                return height.To<int>();
            }

            return height.To<int>();
        }

    }

  1. Resize an Image With the Bitmap Class in C#
  2. Resize an Image With the Graphics.DrawImage() Function in C#

Resize an Image in C#

In this tutorial, we will discuss methods to resize an image in C#.

Resize an Image With the Bitmap Class in C#

The Bitmap class provides many methods to work with images in C#. The Bitmap class gets the pixel data of images. We can resize an image by initializing the Size parameter inside the constructor of the Bitmap class.

The following code example shows us how we can resize an image with the constructor of the Bitmap class in C#.

using System;
using System.Drawing;
namespace resize_image
{
    class Program
    {
        public static Image resizeImage(Image imgToResize, Size size)
        {
            return (Image)(new Bitmap(imgToResize, size));
        }
        static void Main(string[] args)
        {
            string path = "C:\Images\img1.jpg";
            Image img = Image.FromFile(path);
            Bitmap imgbitmap = new Bitmap(img);
            Image resizedImage = resizeImage(imgbitmap, new Size(200, 200));
        }
    }
}

We resized the image img inside the path C:Imagesimg1.jpg with the constructor of the Bitmap class in C#. We created the bitmap imgbitmap to get the pixel data of the image img. We passed the imgbitmap and new Size(100, 100) to the resizeImage() function. The resizeImage() creates a new bitmap with the specified image and size, casts it to image data type, and then returns the value. The value returned by the resizeImage() function is stored inside the resizedImage image.

Resize an Image With the Graphics.DrawImage() Function in C#

The Graphics.DrawImage() function draws an image inside a specified location with specified dimensions in C#. With this method, we can eliminate many drawbacks of resizing an image. The following code example shows us how we can resize an image with the Graphics.DrawImage() function in C#.

using System;
using System.Drawing;
namespace resize_image
{
    class Program
    {
        public static Image resizeImage(Image image, int width, int height)
        {
            var destinationRect = new Rectangle(0, 0, width, height);
            var destinationImage = new Bitmap(width, height);

            destinationImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

            using (var graphics = Graphics.FromImage(destinationImage))
            {
                graphics.CompositingMode = CompositingMode.SourceCopy;
                graphics.CompositingQuality = CompositingQuality.HighQuality;

                using (var wrapMode = new ImageAttributes())
                {
                    wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                    graphics.DrawImage(image, destinationRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
                }
            }

            return (Image) destinationImage;
        }
        static void Main(string[] args)
        {
            string path = "C:\Images\img1.jpg";
            Image img = Image.FromFile(path);
            Bitmap imgbitmap = new Bitmap(img);
            Image resizedImage = resizeImage(imgbitmap, new Size(200, 200));
        }
    }
}

In the above code, the destinationImage.SetResolution() function maintains the dpi of the image regardless of its actual size. The graphics.CompositingMode = CompositingMode.SourceCopy property specifies that when a color is rendered it overwrites the background color. The graphics.CompositingQuality = CompositingQuality.HighQuality property specifies that we only want high quality image to be rendered. The wrapMode.SetWrapMode(WrapMode.TileFlipXY) function prevents ghosting around the image borders. In the end, the graphics.DrawImage() draws the actual image with the specified dimensions.

25 / 19 / 7

Регистрация: 16.08.2013

Сообщений: 1,354

1

.NET 2.x

14.01.2015, 05:53. Показов 6367. Ответов 7


Нужно увеличить пиксельное изображение сохраняя пиксели — пикселями, а не градиентом!

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

14.01.2015, 05:53

Ответы с готовыми решениями:

Изменение размеров элементов, сохраняя пропорции, при изменении размеров самой формы
Как изменять размеры элементов, сохраняя пропорции, при изменении размеров самой формы?

Изменение размеров элементов, при изменение размеров формы
Доброго времени суток, подскажите, как в VS2016 реализовать подобное, а именно:
Имеются следующая…

Изменение размеров рисунка при изменении размеров области вывода (окна)
Нужно сделать так, что бы рисунок менял свой размер при изменении окна…
unit Unit1;
interface

Изменение размеров Image.Picture.LoadFromFile при изменении размеров окна
Подскажите, пожалуйста, какие функции для этого нужны.

7

Hopeco

16 / 16 / 8

Регистрация: 18.03.2014

Сообщений: 268

14.01.2015, 06:16

2

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
using System;
using System.Drawing;
using System.Windows.Forms;
 
namespace TestProgram
{
    public partial class Form1 : Form
    {
        Bitmap bm = new Bitmap("F:\avatar.bmp");
        public Form1()
        {
            InitializeComponent();
 
 
            pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            pictureBox1.Image = bm;
            pictureBox1.Size = new Size(pictureBox1.Width + 10, pictureBox1.Height + 10);
            bm = new Bitmap(pictureBox1.Image);
        }
    }
}

Добавлено через 32 секунды
Так? Просто запихивай в pictureBox а потом достовая и всё Хотя может я просто лох и не понел вопрос.

Добавлено через 8 минут
Ошибочка замени:

C#
1
bm = new Bitmap(pictureBox1.Image);
C#
1
bm = new Bitmap(pictureBox1.Image, pictureBox1.Size);



0



25 / 19 / 7

Регистрация: 16.08.2013

Сообщений: 1,354

14.01.2015, 06:16

 [ТС]

3

Hopeco, Да чтоб тебя, Новичок!
ПРЕЧИТАЙ условие!

— «Нужно увеличить пиксильное ИЗОБРАЖЕНИЕ сохраняя пиксели — пикселями, а не градиентом!»

Т.Е. Не элемент растягивать а «Bitmap»!
И не просто растягивать а растянуть так, что бы небыло такого гг!

Изображения

 



0



25 / 19 / 7

Регистрация: 16.08.2013

Сообщений: 1,354

14.01.2015, 06:20

 [ТС]

4

ты прям вовремя редактируешь…

Добавлено через 2 минуты
Но в любом случае это не подвинуло в правильную сторону!



0



16 / 16 / 8

Регистрация: 18.03.2014

Сообщений: 268

14.01.2015, 06:35

5

Даже не знаю. Нужно каким то образом перевести изображение в векторный формат ( https://ru.wikipedia.org/wiki/… 0%BA%D0%B0) . И то хз (по моему это невозможно, если конечно на изображении не только две линии)



0



kolia4

34 / 39 / 18

Регистрация: 04.05.2013

Сообщений: 212

14.01.2015, 10:40

6

Лучший ответ Сообщение было отмечено Pin1999 как решение

Решение

Pin1999,

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
        Image Zoom(Image image, int k)
        {
            if (k <= 1) return image;
            Bitmap img = new Bitmap(image);
            int width = img.Width;
            int height = img.Height;
            Image zoomImg = new Bitmap(width * k, height * k);
            Graphics g = Graphics.FromImage(zoomImg);
 
            for (int i = 0; i < width; i++)
                for (int j = 0; j < height; j++)
                {
                    Color color = img.GetPixel(i, j);
                    g.FillRectangle(new SolidBrush(color), i * k, j * k, k, k);
                }
 
            return zoomImg;
        }



1



25 / 19 / 7

Регистрация: 16.08.2013

Сообщений: 1,354

14.01.2015, 11:04

 [ТС]

7

kolia4, Спасибо!



0



Storm23

Эксперт .NETАвтор FAQ

10365 / 5096 / 1824

Регистрация: 11.01.2015

Сообщений: 6,226

Записей в блоге: 34

14.01.2015, 12:08

8

C#
1
2
3
4
5
6
7
8
9
10
11
        Bitmap Zoom(Image bmp, Size size)
        {
            var result = new Bitmap(size.Width, size.Height);
            using(var gr = Graphics.FromImage(result))
            {
                gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
                gr.DrawImage(bmp, 0, 0, size.Width, size.Height);
            }
 
            return result;
        }



0



using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Text;

using System.Windows.Forms;

using System.Drawing;

using System.Drawing.Drawing2D;

using System.Drawing.Imaging;

namespace ImageZoom

{

    public partial class Form1 : Form

    {

        private Rectangle selectedArea;

        private Image loadedImage;

        private Image thumbnail;

        private Color selectionColor;

        public Form1()

        {

            InitializeComponent();

            //область масштабирования в эскизе

            selectedArea = new Rectangle(0, 0, 40, 20);

        }

        private void btnOpen_Click(object sender, EventArgs e)

        {

            if (openFileDialog1.ShowDialog() == DialogResult.OK)

            {

                if (loadedImage != null)

                {

                    loadedImage.Dispose();

                    thumbnail.Dispose();

                }

                try

                {

                    loadedImage = Image.FromFile(openFileDialog1.FileName);

                    //Получение контрастного цвета для маркера выделения изображения

                    using (Bitmap bmp = new Bitmap(loadedImage))

                    {

                        selectionColor = GetDominantColor(bmp, false);

                        selectionColor = CalculateOppositeColor(selectionColor);

                    }

                    tZoom.Value = 1;

                    resizePictureArea();

                    updateZoom();

                }

                catch (Exception)

                {

                    MessageBox.Show(«Invalid image»);

                }                

            }

            picSmall.Invalidate();

        }

        /// <summary>

        /// Растягивает выделенную область масштабирования изображения

        /// </summary>

        private Image ZoomImage(Image input, Rectangle zoomArea, Rectangle sourceArea)

        {

            Bitmap newBmp = new Bitmap(sourceArea.Width, sourceArea.Height);

            using (Graphics g = Graphics.FromImage(newBmp))

            {

                //высокая интерполяция

                g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                g.DrawImage(input, sourceArea, zoomArea, GraphicsUnit.Pixel);

            }

            return newBmp;

        }

        /// <summary>

        /// Рисует прямоугольник выделения на изображении

        /// </summary>

        private Image MarkImage(Image input, Rectangle selectedArea, Color selectColor)

        {

            Bitmap newImg = new Bitmap(input.Width, input.Height);

            using (Graphics g = Graphics.FromImage(newImg))

            {

                //Запретить использование внутренних эскизов изображений

                input.RotateFlip(RotateFlipType.Rotate180FlipNone);

                input.RotateFlip(RotateFlipType.Rotate180FlipNone);

                g.DrawImage(input, 0, 0);

                //Изменение размера изображения

                using (Pen p = new Pen(selectColor))

                    g.DrawRectangle(p, selectedArea);

            }

            return (Image)newImg;

        }

        /// <summary>

        /// Изменение размера изображения

        /// </summary>

        private Image ResizeImage(Image input, Size newSize, InterpolationMode interpolation)

        {

            Bitmap newImg = new Bitmap(newSize.Width, newSize.Height);

            using (Graphics g = Graphics.FromImage(newImg))

            {

                //Запретить использование внутренних эскизов изображений

                input.RotateFlip(RotateFlipType.Rotate180FlipNone);

                input.RotateFlip(RotateFlipType.Rotate180FlipNone);

                //Интерполяция

                g.InterpolationMode = interpolation;

                //Нарисуйте изображение с новыми измерениями

                g.DrawImage(input, 0, 0, newSize.Width, newSize.Height);

            }

            return (Image)newImg;

        }

        /// <summary>

        /// Возвращает доминирующий цвет изображения.e

        /// </summary>

        private Color GetDominantColor(Bitmap bmp, bool includeAlpha)

        {

            // GDI+ по-прежнему лжет нам — формат возврата BGRA, а не ARGB.

            BitmapData bmData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height),

                                           ImageLockMode.ReadWrite,

                                           PixelFormat.Format32bppArgb);

            int stride = bmData.Stride;

            IntPtr Scan0 = bmData.Scan0;

            int r = 0;

            int g = 0;

            int b = 0;

            int a = 0;

            int total = 0;

            unsafe

            {

                byte* p = (byte*)(void*)Scan0;

                int nOffset = stride bmp.Width * 4;

                int nWidth = bmp.Width;

                for (int y = 0; y < bmp.Height; y++)

                {

                    for (int x = 0; x < nWidth; x++)

                    {

                        r += p[0];

                        g += p[1];

                        b += p[2];

                        a += p[3];

                        total++;

                        p += 4;

                    }

                    p += nOffset;

                }

            }

            bmp.UnlockBits(bmData);

            r /= total;

            g /= total;

            b /= total;

            a /= total;

            if (includeAlpha)

                return Color.FromArgb(a, r, g, b);

            else

                return Color.FromArgb(r, g, b);

        }

        /// <summary>

        /// Вычисляет цвет, противоположный заданному цвету.

        /// </summary>

        /// <param name=»clr»></param>

        /// <returns></returns>

        private Color CalculateOppositeColor(Color clr)

        {

            return Color.FromArgb(255 clr.R, 255 clr.G, 255 clr.B);

        }

        /// <summary>

        /// Сужает набор заданных размеров, сохраняя при этом соотношение сторон.

        /// </summary>

        private Size ShrinkToDimensions(int originalWidth, int originalHeight, int maxWidth, int maxHeight)

        {

            int newWidth = 0;

            int newHeight = 0;

            if (originalWidth >= originalHeight)

            {

                //Сопоставьте ширину площади с максимальной шириной

                if (originalWidth <= maxWidth)

                {

                    newWidth = originalWidth;

                    newHeight = originalHeight;

                }

                else

                {

                    newWidth = maxWidth;

                    newHeight = originalHeight * maxWidth / originalWidth;

                }

            }

            else

            {

                //Сопоставьте высоту площади с максимальной высотой

                if (originalHeight <= maxHeight)

                {

                    newWidth = originalWidth;

                    newHeight = originalHeight;

                }

                else

                {

                    newWidth = originalWidth * maxHeight / originalHeight;

                    newHeight = maxHeight;

                }

            }

            return new Size(newWidth, newHeight);

        }

        private void resizePictureArea()

        {

            //Создание эскиза изображения (с сохранением пропорций)

            Size newSize = ShrinkToDimensions(loadedImage.Width, loadedImage.Height, 160, 130);

            //используйте низкую интерполяцию

            thumbnail = ResizeImage(loadedImage, new Size(newSize.Width, newSize.Height), InterpolationMode.Low);

            picSmall.Invalidate();

        }

        private void updateZoom()

        {

            if (loadedImage != null)

            {

                //Сопоставление области, выбранной в миниатюре, с фактическим размером изображения

                Rectangle zoomArea = new Rectangle();

                zoomArea.X = selectedArea.X * loadedImage.Width / thumbnail.Width;

                zoomArea.Y = selectedArea.Y * loadedImage.Height / thumbnail.Height;

                zoomArea.Width = selectedArea.Width * loadedImage.Width / thumbnail.Width;

                zoomArea.Height = selectedArea.Height * loadedImage.Height / thumbnail.Height;

                //Настройка выбранной области в соответствии с текущим значением масштаба

                zoomArea.Width /= tZoom.Value;

                zoomArea.Height /= tZoom.Value;

                picZoom.Image = ZoomImage(loadedImage, zoomArea, picZoom.ClientRectangle);

                picZoom.Refresh();

            }

        }

        private void picSmall_Paint(object sender, PaintEventArgs e)

        {

            if (loadedImage != null)

            {

                //Настройка выделенной области в соответствии со значением масштаба

                Rectangle adjustedArea = new Rectangle();

                adjustedArea.X = selectedArea.X;

                adjustedArea.Y = selectedArea.Y;

                adjustedArea.Width = selectedArea.Width / tZoom.Value;

                adjustedArea.Height = selectedArea.Height / tZoom.Value;

                //Рисование выделенной области на эскизе

                picSmall.Image = MarkImage(thumbnail, adjustedArea, selectionColor);

            }

        }

        private void picSmall_Click(object sender, EventArgs e)

        {

            //Обновление выбранной области, когда пользователь нажимает на миниатюру

            Point mouseLoc = picSmall.PointToClient(Cursor.Position);

            selectedArea.X = mouseLoc.X ((selectedArea.Width / tZoom.Value) / 2);

            selectedArea.Y = mouseLoc.Y ((selectedArea.Height / tZoom.Value) / 2);

            //Привязка поля к границам области рисунка

            if (selectedArea.Left < 0)

                selectedArea.X = 0;

            else if (selectedArea.Right > picSmall.Width)

                selectedArea.X = picSmall.Width selectedArea.Width 1;

            if (selectedArea.Top < 0)

                selectedArea.Y = 0;

            else if (selectedArea.Bottom > picSmall.Height)

                selectedArea.Y = picSmall.Height selectedArea.Height 1;

            picSmall.Invalidate();

            updateZoom();

        }

        private void tValue_Scroll(object sender, EventArgs e)

        {

            updateZoom();

        }

    }

}

В приложении, которое я сделал, необходимо было создать функцию с несколькими параметрами. Он довольно большой, но он изменяет размер изображения, может сохранять соотношение сторон и может вырезать края, чтобы вернуть только центр изображения:

/// <summary>
    /// Resize image with a directory as source
    /// </summary>
    /// <param name="OriginalFileLocation">Image location</param>
    /// <param name="heigth">new height</param>
    /// <param name="width">new width</param>
    /// <param name="keepAspectRatio">keep the aspect ratio</param>
    /// <param name="getCenter">return the center bit of the image</param>
    /// <returns>image with new dimentions</returns>
    public Image resizeImageFromFile(String OriginalFileLocation, int heigth, int width, Boolean keepAspectRatio, Boolean getCenter)
    {
        int newheigth = heigth;
        System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(OriginalFileLocation);

        // Prevent using images internal thumbnail
        FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
        FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

        if (keepAspectRatio || getCenter)
        {
            int bmpY = 0;
            double resize = (double)FullsizeImage.Width / (double)width;//get the resize vector
            if (getCenter)
            {
                bmpY = (int)((FullsizeImage.Height - (heigth * resize)) / 2);// gives the Y value of the part that will be cut off, to show only the part in the center
                Rectangle section = new Rectangle(new Point(0, bmpY), new Size(FullsizeImage.Width, (int)(heigth * resize)));// create the section to cut of the original image
                //System.Console.WriteLine("the section that will be cut off: " + section.Size.ToString() + " the Y value is minimized by: " + bmpY);
                Bitmap orImg = new Bitmap((Bitmap)FullsizeImage);//for the correct effect convert image to bitmap.
                FullsizeImage.Dispose();//clear the original image
                using (Bitmap tempImg = new Bitmap(section.Width, section.Height))
                {
                    Graphics cutImg = Graphics.FromImage(tempImg);//              set the file to save the new image to.
                    cutImg.DrawImage(orImg, 0, 0, section, GraphicsUnit.Pixel);// cut the image and save it to tempImg
                    FullsizeImage = tempImg;//save the tempImg as FullsizeImage for resizing later
                    orImg.Dispose();
                    cutImg.Dispose();
                    return FullsizeImage.GetThumbnailImage(width, heigth, null, IntPtr.Zero);
                }
            }
            else newheigth = (int)(FullsizeImage.Height / resize);//  set the new heigth of the current image
        }//return the image resized to the given heigth and width
        return FullsizeImage.GetThumbnailImage(width, newheigth, null, IntPtr.Zero);
    }

Чтобы облегчить доступ к функции, можно добавить некоторые перегруженные функции:

/// <summary>
    /// Resize image with a directory as source
    /// </summary>
    /// <param name="OriginalFileLocation">Image location</param>
    /// <param name="heigth">new height</param>
    /// <param name="width">new width</param>
    /// <returns>image with new dimentions</returns>
    public Image resizeImageFromFile(String OriginalFileLocation, int heigth, int width)
    {
        return resizeImageFromFile(OriginalFileLocation, heigth, width, false, false);
    }

    /// <summary>
    /// Resize image with a directory as source
    /// </summary>
    /// <param name="OriginalFileLocation">Image location</param>
    /// <param name="heigth">new height</param>
    /// <param name="width">new width</param>
    /// <param name="keepAspectRatio">keep the aspect ratio</param>
    /// <returns>image with new dimentions</returns>
    public Image resizeImageFromFile(String OriginalFileLocation, int heigth, int width, Boolean keepAspectRatio)
    {
        return resizeImageFromFile(OriginalFileLocation, heigth, width, keepAspectRatio, false);
    }

Теперь это два последних логических параметра, которые необходимо установить.
Вызовите функцию следующим образом:

System.Drawing.Image ResizedImage = resizeImageFromFile(imageLocation, 800, 400, true, true);

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Как изменить размер background html
  • Как изменить размер background color css
  • Как изменить размер arraylist java
  • Как изменить разделы на внешнем жестком диске
  • Как изменить разделы диска на виндовс 7

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии