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

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

Для этого примера требуются следующие компоненты

  • Приложение Windows Forms.

  • Объект PaintEventArgs, являющийся параметром PaintEventHandler.

How to: Convert a BMP image to a PNG image

Oftentimes, you will want to convert from one image file format to another. You can do this conversion easily by calling the Save method of the Image class and specifying the ImageFormat for the desired image file format.

Example

The following example loads a BMP image from a type, and saves the image in the PNG format.

private void SaveBmpAsPNG()

{

Bitmap bmp1 = new Bitmap(typeof(Button), "Button.bmp");

bmp1.Save(@"c:\button.png", ImageFormat.Png);

}

Compiling the Code

This example requires:

  • A Windows Forms application.

How to: Set JPEG Compression Level

You may want to modify the parameters of an image when you save the image to disk to minimize the file size or improve its quality. You can adjust the quality of a JPEG image by modifying its compression level. To specify the compression level when you save a JPEG image, you must create an EncoderParameters object and pass it to the Save method of the Image class. Initialize the EncoderParameters object so that it has an array that consists of one EncoderParameter. When you create the EncoderParameter, specify the Quality encoder, and the desired compression level.

Example

The following example code creates an EncoderParameter object and saves three JPEG images. Each JPEG image is saved with a different quality level, by modifying the long value passed to the EncoderParameter constructor. A quality level of 0 corresponds to the greatest compression, and a quality level of 100 corresponds to the least compression.

Преобразование изображение из формата BMP в формат PNG

Очень часто возникает необходимость в преобразовании изображения из одного формата в другой. Для этого необходимо вызвать метод Save класса Image и указать в качестве параметра ImageFormat нужный формат файла.

Пример

Следующий пример загружает изображение в формате BMP и сохраняет его в формате PNG.

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

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

Для этого примера требуются следующие компоненты.

  • Приложение Windows Forms.

Установка уровня сжатия JPEG

Чтобы сделать размер файла сохраняемого на диске изображения минимальным или улучшить его качество, может потребоваться изменить параметры изображения. Для изменения качества изображения JPEG можно изменить его уровень сжатия. Чтобы указать уровень сжатия при сохранении изображения в формате JPEG, необходимо создать объект EncoderParameters и передать его методу Save класса Image. Инициализируйте объект EncoderParameters, чтобы он включал массив из одного объекта EncoderParameter. При создании объекта EncoderParameter укажите кодировщик Quality и выберите нужный уровень сжатия.

Пример

Следующий пример создает объект EncoderParameter и сохраняет три изображения JPEG. Каждое изображение JPEG сохраняется со своим уровнем качества, для этого необходимо изменить значение типа long, передаваемое конструктору EncoderParameter. Уровень качества 0 соответствует максимальному сжатию, а уровень качества 100 — минимальному сжатию.

private void VaryQualityLevel()

{

// Get a bitmap.

Bitmap bmp1 = new Bitmap(@"c:\TestPhoto.jpg");

ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);

// Create an Encoder object based on the GUID

// for the Quality parameter category.

System.Drawing.Imaging.Encoder myEncoder =

System.Drawing.Imaging.Encoder.Quality;

// Create an EncoderParameters object.

// An EncoderParameters object has an array of EncoderParameter

// objects. In this case, there is only one

// EncoderParameter object in the array.

EncoderParameters myEncoderParameters = new EncoderParameters(1);

EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L);

myEncoderParameters.Param[0] = myEncoderParameter;

bmp1.Save(@"c:\TestPhotoQualityFifty.jpg", jgpEncoder, myEncoderParameters);

myEncoderParameter = new EncoderParameter(myEncoder, 100L);

myEncoderParameters.Param[0] = myEncoderParameter;

bmp1.Save(@"c:\TestPhotoQualityHundred.jpg", jgpEncoder, myEncoderParameters);

// Save the bitmap as a JPG file with zero quality level compression.

myEncoderParameter = new EncoderParameter(myEncoder, 0L);

myEncoderParameters.Param[0] = myEncoderParameter;

bmp1.Save(@"c:\TestPhotoQualityZero.jpg", jgpEncoder, myEncoderParameters);

}

...

private ImageCodecInfo GetEncoder(ImageFormat format)

{

ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();

foreach (ImageCodecInfo codec in codecs)

{

if (codec.FormatID == format.Guid)

{

return codec;

}

}

return null;

}

Compiling the Code

This example requires:

  • A Windows Forms application.

  • A PaintEventArgs, which is a parameter of PaintEventHandler.

  • An image file that is named TestPhoto.jpg and located at c:\.

----