Домой Convert Конвертируем Image в Icon: Справочник по C#

Конвертируем Image в Icon: Справочник по C#

605
0


Данный пример показывает как легко преобразовать любое изображение в иконку(*.ico).
Для работы вам необходимо подключить пространство имен:

using System.Drawing;
using System.IO;

Функция:

private Icon MakeIcon(Image img, int size, bool keepAspectRatio)
{
Bitmap square = new Bitmap(size, size); // create new bitmap
Graphics g = Graphics.FromImage(square); // allow drawing to it

int x, y, w, h; // dimensions for new image

if (!keepAspectRatio || img.Height == img.Width)
{
// just fill the square
x = y = 0; // set x and y to 0
w = h = size; // set width and height to size
}
else
{
// work out the aspect ratio
float r = (float)img.Width / (float)img.Height;

// set dimensions accordingly to fit inside size^2 square
if (r > 1)
{ // w is bigger, so divide h by r
w = size;
h = (int)((float)size / r);
x = 0; y = (size - h) / 2; // center the image
}
else
{ // h is bigger, so multiply w by r
w = (int)((float)size * r);
h = size;
y = 0; x = (size - w) / 2; // center the image
}
}
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(img, x, y, w, h);
g.Flush();
return Icon.FromHandle(square.GetHicon());
}

Пример использования функции:

private void button2_Click(object sender, System.EventArgs e)
{
Image img = Image.FromFile(@"D:p.png");
Icon ic = MakeIcon(img, 128, false);
using (FileStream fs = new FileStream(@"D:p1.ico", FileMode.Create))
ic.Save(fs);
}

ЧИТАТЬ ТАКЖЕ:  Вставка изображения в PictureBox из буфера обмена: Справочник по C#

Конвертируем Image в Icon: Справочник по C#

0.00 (0%) 0 votes

ОСТАВЬТЕ ОТВЕТ

Пожалуйста, введите ваш комментарий!
пожалуйста, введите ваше имя здесь