Posted By

ax4413 on 06/30/10


Tagged

resize image c thumbnail


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

Vordreller
digiteyes
Tyster
mheinrich


Resize Images Keeping Aspect Ratio


 / Published in: C#
 

  1. /// <summary>
  2. /// Allows for image resizing. if AllowLargerImageCreation = true
  3. /// you want to increase the size of the image
  4. /// </summary>
  5. /// <param name="bytes"></param>
  6. /// <param name="NewWidth"></param>
  7. /// <param name="MaxHeight"></param>
  8. /// <param name="AllowLargerImageCreation"></param>
  9. /// <returns></returns>
  10. /// <remarks></remarks>
  11. public static byte[] ResizeImage(byte[] bytes, int NewWidth, int MaxHeight, bool AllowLargerImageCreation)
  12. {
  13.  
  14. Image FullsizeImage = null;
  15. Image ResizedImage = null;
  16. //Cast bytes to an image
  17. FullsizeImage = byteArrayToImage(bytes);
  18.  
  19. // Prevent using images internal thumbnail
  20. FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
  21. FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
  22.  
  23. // If we are re sizing upwards to a bigger size
  24. if (AllowLargerImageCreation) {
  25. if (FullsizeImage.Width <= NewWidth) {
  26. NewWidth = FullsizeImage.Width;
  27. }
  28. }
  29.  
  30. //Keep aspect ratio
  31. int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;
  32. if (NewHeight > MaxHeight) {
  33. // Resize with height instead
  34. NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;
  35. NewHeight = MaxHeight;
  36. }
  37.  
  38. ResizedImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);
  39.  
  40. // Clear handle to original file so that we can overwrite it if necessary
  41. FullsizeImage.Dispose();
  42.  
  43. return imageToByteArray(ResizedImage);
  44. }
  45.  
  46.  
  47. /// <summary>
  48. /// convert image to byte array
  49. /// </summary>
  50. /// <param name="imageIn"></param>
  51. /// <returns></returns>
  52. private static byte[] imageToByteArray(System.Drawing.Image imageIn)
  53. {
  54. MemoryStream ms = new MemoryStream();
  55. imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
  56. return ms.ToArray();
  57. }
  58.  
  59.  
  60. /// <summary>
  61. /// Convert a byte array to an image
  62. /// </summary>
  63. /// <remarks></remarks>
  64. public static Image byteArrayToImage(byte[] byteArrayIn)
  65. {
  66. MemoryStream ms = new MemoryStream(byteArrayIn);
  67. Image returnImage = Image.FromStream(ms);
  68. return returnImage;
  69. }

Report this snippet  

You need to login to post a comment.