Tuesday, December 30, 2008

Convert Image to Icon in .Net

  1. ///
  2. /// Converts an image into an icon.
  3. ///
  4. /// The image that shall become an icon
  5. /// The width and height of the icon. Standard
  6. /// sizes are 16x16, 32x32, 48x48, 64x64.
  7. /// Whether the image should be squashed into a
  8. /// square or whether whitespace should be put around it.
  9. /// An icon!!
  10. private Icon MakeIcon(Image img, int size, bool keepAspectRatio) {
  11. Bitmap square = new Bitmap(size, size); // create new bitmap
  12. Graphics g = Graphics.FromImage(square); // allow drawing to it
  13. int x, y, w, h; // dimensions for new image
  14. if(!keepAspectRatio || img.Height == img.Width) {
  15. // just fill the square
  16. x = y = 0; // set x and y to 0
  17. w = h = size; // set width and height to size
  18. } else {
  19. // work out the aspect ratio
  20. float r = (float)img.Width / (float)img.Height;
  21. // set dimensions accordingly to fit inside size^2 square
  22. if(r > 1) { // w is bigger, so divide h by r
  23. w = size;
  24. h = (int)((float)size / r);
  25. x = 0; y = (size - h) / 2; // center the image
  26. } else { // h is bigger, so multiply w by r
  27. w = (int)((float)size * r);
  28. h = size;
  29. y = 0; x = (size - w) / 2; // center the image
  30. }
  31. }
  32. // make the image shrink nicely by using HighQualityBicubic mode
  33. g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
  34. g.DrawImage(img, x, y, w, h); // draw image with specified dimensions
  35. g.Flush(); // make sure all drawing operations complete before we get the icon
  36. // following line would work directly on any image, but then
  37. // it wouldn't look as nice.
  38. return Icon.FromHandle(square.GetHicon());
  39. }

No comments: