Конвертируем Image в Icon


Данный пример показывает как легко преобразовать любое изображение в иконку(*.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);           
}


1 комментарий:

  1. Доброго времени суток, программа работает отлично, но как сохранить чоткость и цветность как в оригинале? а то получается не очень хорошо.

    ОтветитьУдалить

Большая просьба, не писать в комментариях всякую ерунду не по теме!