Mega Code Archive

 
Categories / C# / 2D Graphics
 

Create Icon from Image

using System; using System.Collections.Generic; using System.Linq; using System.Drawing; using System.Text; public class Common {     public static Icon MakeIcon(Image img, int size, bool keepAspRatio)     {         Bitmap square = new Bitmap(size, size);         Graphics g = Graphics.FromImage(square);         int x, y, w, h;         if (!keepAspRatio || img.Height == img.Width)         { x = y = 0; w = h = size; }         else         {             float r = (float)img.Width / (float)img.Height;             if (r > 1)             {                 w = size; h = (int)((float)size / r);                 x = 0; y = (size - h) / 2;             }             else             {                 w = (int)((float)size * r);                 h = size; y = 0; x = (size - w) / 2;             }         }         g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;         g.DrawImage(img, x, y, w, h); g.Flush();         return Icon.FromHandle(square.GetHicon());     } }