andrew4582

ImageResizer

Aug 18th, 2010
237
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.05 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Drawing;
  6. using System.Drawing.Drawing2D;
  7. using System.Drawing.Imaging;
  8. using System.IO;
  9.  
  10. namespace Core.Drawing {
  11.  
  12.     public class ImageResizer {
  13.  
  14.         public static void ResizeImage(string originalFile,string newFile,Size size,bool resizeExactly = false) {
  15.             ResizeImage(originalFile,newFile,size.Width,size.Height,resizeExactly: resizeExactly,onlyResizeIfWider:false);
  16.         }
  17.         public static void ResizeImage(string originalFile,string newFile,int newWidth,int maxHeight,bool resizeExactly, bool onlyResizeIfWider = false) {
  18.  
  19.             using(Image fullsizeImage = Image.FromFile(originalFile)) {
  20.  
  21.                 // Prevent using images internal thumbnail
  22.                 fullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
  23.                 fullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
  24.                 int newHeight = maxHeight;
  25.  
  26.                 if(resizeExactly == false) {
  27.                     if(onlyResizeIfWider) {
  28.                         if(fullsizeImage.Width <= newWidth) {
  29.                             newWidth = fullsizeImage.Width;
  30.                         }
  31.                     }
  32.  
  33.                     newHeight = fullsizeImage.Height * newWidth / fullsizeImage.Width;
  34.                     if(newHeight > maxHeight) {
  35.                         // Resize with height instead
  36.                         newWidth = fullsizeImage.Width * maxHeight / fullsizeImage.Height;
  37.                         newHeight = maxHeight;
  38.                     }
  39.                 }
  40.  
  41.                 using(Image newImage = fullsizeImage.GetThumbnailImage(newWidth,newHeight,null,IntPtr.Zero)) {
  42.  
  43.                     // Clear handle to original file so that we can overwrite it if necessary
  44.                     fullsizeImage.Dispose();
  45.                    
  46.                     // Save resized picture
  47.                     newImage.Save(newFile);
  48.                 }
  49.             }
  50.         }
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment