Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp_Graphics.doc
Скачиваний:
20
Добавлен:
16.11.2019
Размер:
3.1 Mб
Скачать

Компиляция кода

Предыдущий пример предназначен для работы с Windows Forms, для него необходим объект PaintEventArgs e, передаваемый в качестве параметра обработчику события Paint. Не забудьте заменить путь и имя файла Stripes.bmp именем файла изображения и путем к нему в вашей системе.

How to: Use Interpolation Mode to Control Image Quality During Scaling

The interpolation mode of a Graphics object influences the way GDI+ scales (stretches and shrinks) images. The InterpolationMode enumeration defines several interpolation modes, some of which are shown in the following list:

  • NearestNeighbor

  • Bilinear

  • HighQualityBilinear

  • Bicubic

  • HighQualityBicubic

To stretch an image, each pixel in the original image must be mapped to a group of pixels in the larger image. To shrink an image, groups of pixels in the original image must be mapped to single pixels in the smaller image. The effectiveness of the algorithms that perform these mappings determines the quality of a scaled image. Algorithms that produce higher-quality scaled images tend to require more processing time. In the preceding list, NearestNeighbor is the lowest-quality mode and HighQualityBicubic is the highest-quality mode.

To set the interpolation mode, assign one of the members of the InterpolationMode enumeration to the InterpolationMode property of a Graphics object.

Example

The following example draws an image and then shrinks the image with three different interpolation modes.

The following illustration shows the original image and the three smaller images.

Использование режима интерполяции для управления качеством изображений при масштабировании

Режим интерполяции объекта Graphics влияет на способ, с помощью которого GDI+ масштабирует (растягивает и сжимает) изображения. Перечисление InterpolationMode определяет различные режимы интерполяции, некоторые из которых приведены в следующем списке:

  • NearestNeighbor

  • Bilinear

  • HighQualityBilinear

  • Bicubic

  • HighQualityBicubic

Чтобы растянуть изображение, каждая точка этого исходного изображения должна быть сопоставлена группе точек увеличенного изображения. Чтобы сжать изображение, группы точек этого исходного изображения должны быть сопоставлены отдельным точкам уменьшенного изображения. Качество масштабированного изображения определяется алгоритмами, используемыми для осуществления этих сопоставлений. Алгоритмы, создающие более качественные масштабированные изображения, обычно требуют больших затрат машинного времени. Из методов интерполяции, приведенных в предыдущем списке, NearestNeighbor обеспечивает наихудшее качество, а HighQualityBicubic — наилучшее.

Чтобы установить режим интерполяции, присвойте один из членов перечисления InterpolationMode свойству InterpolationMode объекта Graphics.

Пример

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

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

-----------

Image image = new Bitmap("GrapeBunch.bmp");

int width = image.Width;

int height = image.Height;

// Draw the image with no shrinking or stretching.

e.Graphics.DrawImage(

image,

new Rectangle(10, 10, width, height), // destination rectangle

0,

0, // upper-left corner of source rectangle

width, // width of source rectangle

height, // height of source rectangle

GraphicsUnit.Pixel,

null);

// Shrink the image using low-quality interpolation.

e.Graphics.InterpolationMode = InterpolationMode.NearestNeighbor;

e.Graphics.DrawImage(

image,

new Rectangle(10, 250, (int)(0.6 * width), (int)(0.6 * height)),

// destination rectangle

0,

0, // upper-left corner of source rectangle

width, // width of source rectangle

height, // height of source rectangle

GraphicsUnit.Pixel);

// Shrink the image using medium-quality interpolation.

e.Graphics.InterpolationMode = InterpolationMode.HighQualityBilinear;

e.Graphics.DrawImage(

image,

new Rectangle(150, 250, (int)(0.6 * width), (int)(0.6 * height)),

// destination rectangle

0,

0, // upper-left corner of source rectangle

width, // width of source rectangle

height, // height of source rectangle

GraphicsUnit.Pixel);

// Shrink the image using high-quality interpolation.

e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

e.Graphics.DrawImage(

image,

new Rectangle(290, 250, (int)(0.6 * width), (int)(0.6 * height)),

// destination rectangle

0,

0, // upper-left corner of source rectangle

width, // width of source rectangle

height, // height of source rectangle

GraphicsUnit.Pixel);

Compiling the Code

The preceding example is designed for use with Windows Forms, and it requires PaintEventArgs e, which is a parameter of the Paint event handler.

-------------