ImageResizer

Finite le vacanze, tutti a metter le proprie foto online. Ecco una piccola utility (frutto di refactoring e copia/incolla)  per ridimensionare ed alleggerire le immagini in un formato adatto al web:

Program.cs

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Linq;
   4: using System.Text;
   5: using System.IO;
   6:
   7: namespace ImageResizer
   8: {
   9:     class Program
  10:     {
  11:         static void Main(string[] args)
  12:         {
  13:             Console.WriteLine("Seleziona cartella :");
  14:             string folder = Console.ReadLine();
  15:             Console.WriteLine("Seleziona larghezza immagine (es: 1024) :");
  16:             int width = Convert.ToInt32(Console.ReadLine());
  17:             Console.WriteLine("Seleziona altezza immagine (es: 768) :");
  18:             int height = Convert.ToInt32(Console.ReadLine());
  19:             Console.WriteLine("Seleziona qualità (0 - 100):");
  20:             int quality = Convert.ToInt32(Console.ReadLine());
  21:             string newFolder = folder + "_resized";
  22:             List<string> files = Directory.GetFiles(folder).ToList();
  23:             Directory.CreateDirectory(newFolder);
  24:
  25:             foreach (string file in files)
  26:             {
  27:                 ImageUtilities.ResizeImage(file, (newFolder + "\" + Path.GetFileName(file)), width, height, true, quality);
  28:             }
  29:
  30:         }
  31:
  32:     }
  33: }

E la classe che si occupa del lavoro sporco, ImageUtilities.cs

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Linq;
   4: using System.Text;
   5: using System.Drawing;
   6: using System.Drawing.Imaging;
   7:
   8: namespace ImageResizer
   9: {
  10:     /// <summary>
  11:     /// Provides various image untilities, such as high quality resizing and the ability to save a JPEG.
  12:     /// </summary>
  13:     public static class ImageUtilities
  14:     {
  15:         /// <summary>
  16:         /// A quick lookup for getting image encoders
  17:         /// </summary>
  18:         private static Dictionary<string, ImageCodecInfo> encoders = null;
  19:
  20:         /// <summary>
  21:         /// A quick lookup for getting image encoders
  22:         /// </summary>
  23:         public static Dictionary<string, ImageCodecInfo> Encoders
  24:         {
  25:             //get accessor that creates the dictionary on demandd
  26:             get
  27:             {
  28:                 //if the quick lookup isn't initialised, initialise it
  29:                 if (encoders == null)
  30:                 {
  31:                     encoders = new Dictionary<string, ImageCodecInfo>();
  32:                 }
  33:
  34:                 //if there are no codecs, try loading them
  35:                 if (encoders.Count == 0)
  36:                 {
  37:                     //get all the codecs
  38:                     foreach (ImageCodecInfo codec in ImageCodecInfo.GetImageEncoders())
  39:                     {
  40:                         //add each codec to the quick lookup
  41:                         encoders.Add(codec.MimeType.ToLower(), codec);
  42:                     }
  43:                 }
  44:
  45:                 //return the lookup
  46:                 return encoders;
  47:             }
  48:         }
  49:
  50:         public static void ResizeImage(string OriginalFile, string NewFile, int NewWidth, int MaxHeight, bool OnlyResizeIfWider, int quality)
  51:         {
  52:             System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(OriginalFile);
  53:
  54:             // Prevent using images internal thumbnail
  55:             FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
  56:             FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
  57:
  58:             if (OnlyResizeIfWider)
  59:             {
  60:                 if (FullsizeImage.Width <= NewWidth)
  61:                 {
  62:                     NewWidth = FullsizeImage.Width;
  63:                 }
  64:             }
  65:
  66:             int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;
  67:             if (NewHeight > MaxHeight)
  68:             {
  69:                 // Resize with height instead
  70:                 NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;
  71:                 NewHeight = MaxHeight;
  72:             }
  73:
  74:             System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);
  75:
  76:             // Clear handle to original file so that we can overwrite it if necessary
  77:             FullsizeImage.Dispose();
  78:
  79:             // Save resized picture
  80:             //NewImage.Save(NewFile);
  81:             SaveJpeg(NewFile, NewImage, quality);
  82:         }
  83:
  84:
  85:         /// <summary> 
  86:         /// Saves an image as a jpeg image, with the given quality 
  87:         /// </summary> 
  88:         /// <param name="path">Path to which the image would be saved.</param> 
  89:         /// <param name="quality">An integer from 0 to 100, with 100 being the 
  90:         /// highest quality</param> 
  91:         /// <exception cref="ArgumentOutOfRangeException">
  92:         /// An invalid value was entered for image quality.
  93:         /// </exception>
  94:         public static void SaveJpeg(string path, Image image, int quality)
  95:         {
  96:             //ensure the quality is within the correct range
  97:             if ((quality < 0) || (quality > 100))
  98:             {
  99:                 //create the error message
 100:                 string error = string.Format("La qualita' dell'immagine deve essere compresa tra 0 e 100.  Il valore {0} non e' valido.", quality);
 101:                 //throw a helpful exception
 102:                 throw new ArgumentOutOfRangeException(error);
 103:             }
 104:
 105:             //create an encoder parameter for the image quality
 106:             EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
 107:             //get the jpeg codec
 108:             ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");
 109:
 110:             //create a collection of all parameters that we will pass to the encoder
 111:             EncoderParameters encoderParams = new EncoderParameters(1);
 112:             //set the quality parameter for the codec
 113:             encoderParams.Param[0] = qualityParam;
 114:             //save the image using the codec and the parameters
 115:             image.Save(path, jpegCodec, encoderParams);
 116:         }
 117:
 118:         /// <summary> 
 119:         /// Returns the image codec with the given mime type 
 120:         /// </summary> 
 121:         public static ImageCodecInfo GetEncoderInfo(string mimeType)
 122:         {
 123:             //do a case insensitive look at the mime type
 124:             mimeType = mimeType.ToLower();
 125:
 126:             //the codec to return, default to null
 127:             ImageCodecInfo foundCodec = null;
 128:
 129:             //if we have the encoder, get it to return
 130:             if (Encoders.ContainsKey(mimeType))
 131:             {
 132:                 //pull the codec from the lookup
 133:                 foundCodec = Encoders[mimeType];
 134:             }
 135:
 136:             return foundCodec;
 137:         }
 138:     }
 139:
 140: }



No Comments


You can leave the first : )