Resize Image In C#

In this article, you will come to know about the followings things:

  1. File Upload
  2. Resize image proportionate Ratio and Store in JPG format.

For details, refer to the following link.

Here, I had used the link given above and customized it as per my project requirement. This is basically a tool to resize the image. Create a Imager.cs class to achieve the same.

I had used following namespaces:

Namespace Name

Description

Link

System.Drawing;

To provide access to GDI+ basic graphics functionality

https://msdn.microsoft.com/en-us/library/system.drawing(v=vs.110).aspx

System.Drawing.Drawing2D;

To provide advanced two-dimensional and vector graphics functionality

https://msdn.microsoft.com/en-us/library/system.drawing.drawing2d(v=vs.110).aspx

System.Drawing.Imaging;

To provide advanced GDI+ imaging functionality. Basic graphics functionality is provided by the System.Drawing namespace.

https://msdn.microsoft.com/en-us/library/system.drawing.imaging(v=vs.110).aspx

System.IO;

To allow reading and writing to the files and data streams.

https://msdn.microsoft.com/en-us/library/system.io(v=vs.110).aspx

Under System.Drawing, you will have following namespaces:

  1. System.Drawing.Configuration.
  2. System.Drawing.Design.
  3. System.Drawing.Drawing2D
  4. System.Drawing.Imaging
  5. System.Drawing.Printing
  6. System.Drawing.Text

Note: Classes within the System.Drawing namespace are not supported for use within a Windows or ASP.NET Service.

METHODS NAME

DESCRIPTION

public static void SaveJpeg(string path, Image img)

Save an image as jpeg

public static void Save(string path, Image img, ImageCodecInfo imageCodecInfo)

Save an image

public static ImageCodecInfo GetEncoderInfo(string mimeType)

Information regarding EncoderInfo

public static Image PutOnCanvas(Image image, int width, int height, Color canvasColor)

The image remains the same size, and it is placed in the middle of the new canvas

public static Image PutOnWhiteCanvas(Image image, int width, int height)

 

public static Image Resize(Image image, int newWidth, int maxHeight, bool onlyResizeIfWider)

Resize an image and maintain aspect ratio

public static Image Crop(Image img, Rectangle cropArea)

To crop the image.

public static byte[] imageToByteArray(System.Drawing.Image imageIn)

To convert a image into byte code array.

public static Image byteArrayToImage(byte[] byteArrayIn)

To create an image from byte array to image format.

Code Explanations

  1. protected void btnSubmit_Click(object sender, EventArgs e)  
  2.     {  
  3.         string filename = Path.GetFileName(fuImage.PostedFile.FileName);  
  4.         //string str = DateTime.Now.ToString("hhmmssffffff") + filename;  
  5.         string str = filename;  
  6.         fuImage.SaveAs(Server.MapPath("ImgDir/" + str));  
  7.         string imgPath = "D:\\RND_Project\\ImageResize\\ImgDir\\";  
  8.           
  9.         Imager.PerformImageResizeAndPutOnCanvas(imgPath,filename, Convert.ToInt16(txtWidth.Text), Convert.ToInt16(txtHeight.Text), txtOutputFileName.Text.ToString()+".jpg");  
  10.   
  11.     }  
As you can see in the code, given above, to resize image, we have to upload an image, followed by calling Imager.PerformImageResizeAndPutOnCanvas() is a function to perform our task.

PerformImageResizeAndPutOnCanvas() : Function detail
  1. public static void PerformImageResizeAndPutOnCanvas(string pFilePath, string pFileName, int pWidth, int pHeight,string pOutputFileName )  
  2.         {  
  3.               
  4.             System.Drawing.Image imgBef;  
  5.             imgBef = System.Drawing.Image.FromFile(pFilePath + pFileName);  
  6.   
  7.   
  8.             System.Drawing.Image _imgR;  
  9.             _imgR = Imager.Resize(imgBef, pWidth, pHeight, true);  
  10.   
  11.   
  12.             System.Drawing.Image _img2;  
  13.             _img2 = Imager.PutOnCanvas(_imgR, pWidth, pHeight, System.Drawing.Color.White);  
  14.   
  15.             //Save JPEG  
  16.             SaveJpeg(pFilePath + pOutputFileName, _img2);  
  17.   
  18.         }  
As you must have seen, above: 
  1. First, I had called FromFile method of System.Drawing.Image, which coverts an uploaded file into System.Drawing.Image.
  2. Resize function of Imager.cs resizes the image. There is a last boolean parameter, which conditionally works (only Resize If Wider).
  3. PutOnCanvas function of Imager.cs puts the image on virtually created canvas for an image.
  4. SaveJpeg is a last method to be called to save the file in JPEG format.

Imager.cs

  1. using System;  
  2. using System.Drawing;  
  3. using System.Drawing.Drawing2D;  
  4. using System.Drawing.Imaging;  
  5. using System.IO;  
  6. using System.Linq;  
  7. using System.Web;  
  8.   
  9. namespace ImagerLib  
  10. {  
  11.     public static class Imager  
  12.     {  
  13.         /// <summary>  
  14.         /// Save image as jpeg  
  15.         /// </summary>  
  16.         /// <param name="path">path where to save</param>  
  17.         /// <param name="img">image to save</param>  
  18.         public static void SaveJpeg(string path, Image img)  
  19.         {  
  20.             var qualityParam = new EncoderParameter(Encoder.Quality, 100L);  
  21.             var jpegCodec = GetEncoderInfo("image/jpeg");  
  22.   
  23.             var encoderParams = new EncoderParameters(1);  
  24.             encoderParams.Param[0] = qualityParam;  
  25.             img.Save(path, jpegCodec, encoderParams);  
  26.         }  
  27.   
  28.         /// <summary>  
  29.         /// Save image  
  30.         /// </summary>  
  31.         /// <param name="path">path where to save</param>  
  32.         /// <param name="img">image to save</param>  
  33.         /// <param name="imageCodecInfo">codec info</param>  
  34.         public static void Save(string path, Image img, ImageCodecInfo imageCodecInfo)  
  35.         {  
  36.             var qualityParam = new EncoderParameter(Encoder.Quality, 100L);  
  37.   
  38.             var encoderParams = new EncoderParameters(1);  
  39.             encoderParams.Param[0] = qualityParam;  
  40.             img.Save(path, imageCodecInfo, encoderParams);  
  41.         }  
  42.   
  43.         /// <summary>  
  44.         /// get codec info by mime type  
  45.         /// </summary>  
  46.         /// <param name="mimeType"></param>  
  47.         /// <returns></returns>  
  48.         public static ImageCodecInfo GetEncoderInfo(string mimeType)  
  49.         {  
  50.             return ImageCodecInfo.GetImageEncoders().FirstOrDefault(t => t.MimeType == mimeType);  
  51.         }  
  52.   
  53.         /// <summary>  
  54.         /// the image remains the same size, and it is placed in the middle of the new canvas  
  55.         /// </summary>  
  56.         /// <param name="image">image to put on canvas</param>  
  57.         /// <param name="width">canvas width</param>  
  58.         /// <param name="height">canvas height</param>  
  59.         /// <param name="canvasColor">canvas color</param>  
  60.         /// <returns></returns>  
  61.         public static Image PutOnCanvas(Image image, int width, int height, Color canvasColor)  
  62.         {  
  63.             var res = new Bitmap(width, height);  
  64.             using (var g = Graphics.FromImage(res))  
  65.             {  
  66.                 g.Clear(canvasColor);  
  67.                 var x = (width - image.Width) / 2;  
  68.                 var y = (height - image.Height) / 2;  
  69.                 g.DrawImageUnscaled(image, x, y, image.Width, image.Height);  
  70.             }  
  71.   
  72.             return res;  
  73.         }  
  74.   
  75.         /// <summary>  
  76.         /// the image remains the same size, and it is placed in the middle of the new canvas  
  77.         /// </summary>  
  78.         /// <param name="image">image to put on canvas</param>  
  79.         /// <param name="width">canvas width</param>  
  80.         /// <param name="height">canvas height</param>  
  81.         /// <returns></returns>  
  82.         public static Image PutOnWhiteCanvas(Image image, int width, int height)  
  83.         {  
  84.             return PutOnCanvas(image, width, height, Color.White);  
  85.         }  
  86.   
  87.         /// <summary>  
  88.         /// resize an image and maintain aspect ratio  
  89.         /// </summary>  
  90.         /// <param name="image">image to resize</param>  
  91.         /// <param name="newWidth">desired width</param>  
  92.         /// <param name="maxHeight">max height</param>  
  93.         /// <param name="onlyResizeIfWider">if image width is smaller than newWidth use image width</param>  
  94.         /// <returns>resized image</returns>  
  95.         public static Image Resize(Image image, int newWidth, int maxHeight, bool onlyResizeIfWider)  
  96.         {  
  97.             if (onlyResizeIfWider && image.Width <= newWidth) newWidth = image.Width;  
  98.   
  99.             var newHeight = image.Height * newWidth / image.Width;  
  100.             if (newHeight > maxHeight)  
  101.             {  
  102.                 // Resize with height instead  
  103.                 newWidth = image.Width * maxHeight / image.Height;  
  104.                 newHeight = maxHeight;  
  105.             }  
  106.   
  107.             var res = new Bitmap(newWidth, newHeight);  
  108.   
  109.             using (var graphic = Graphics.FromImage(res))  
  110.             {  
  111.                 graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;  
  112.                 graphic.SmoothingMode = SmoothingMode.HighQuality;  
  113.                 graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;  
  114.                 graphic.CompositingQuality = CompositingQuality.HighQuality;  
  115.                 graphic.DrawImage(image, 0, 0, newWidth, newHeight);  
  116.             }  
  117.   
  118.             return res;  
  119.         }  
  120.   
  121.         /// <summary>  
  122.         /// Crop an image   
  123.         /// </summary>  
  124.         /// <param name="img">image to crop</param>  
  125.         /// <param name="cropArea">rectangle to crop</param>  
  126.         /// <returns>resulting image</returns>  
  127.         public static Image Crop(Image img, Rectangle cropArea)  
  128.         {  
  129.             var bmpImage = new Bitmap(img);  
  130.             var bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);  
  131.             return bmpCrop;  
  132.         }  
  133.   
  134.         public static byte[] imageToByteArray(System.Drawing.Image imageIn)  
  135.         {  
  136.             MemoryStream ms = new MemoryStream();  
  137.             imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);  
  138.             return ms.ToArray();  
  139.         }  
  140.   
  141.         public static Image byteArrayToImage(byte[] byteArrayIn)  
  142.         {  
  143.             MemoryStream ms = new MemoryStream(byteArrayIn);  
  144.             Image returnImage = Image.FromStream(ms);  
  145.             return returnImage;  
  146.         }  
  147.   
  148.         //The actual converting function  
  149.         public static string GetImage(object img)  
  150.         {  
  151.             return "data:image/jpg;base64," + Convert.ToBase64String((byte[])img);  
  152.         }  
  153.   
  154.   
  155.         public static void PerformImageResizeAndPutOnCanvas(string pFilePath, string pFileName, int pWidth, int pHeight,string pOutputFileName )  
  156.         {  
  157.               
  158.             System.Drawing.Image imgBef;  
  159.             imgBef = System.Drawing.Image.FromFile(pFilePath + pFileName);  
  160.   
  161.   
  162.             System.Drawing.Image _imgR;  
  163.             _imgR = Imager.Resize(imgBef, pWidth, pHeight, true);  
  164.   
  165.   
  166.             System.Drawing.Image _img2;  
  167.             _img2 = Imager.PutOnCanvas(_imgR, pWidth, pHeight, System.Drawing.Color.White);  
  168.   
  169.             //Save JPEG  
  170.             Imager.SaveJpeg(pFilePath + pOutputFileName, _img2);  
  171.   
  172.         }  
  173.     }  
  174. }  
Example:

Image1 : In this image, you can see, I had uploaded or you can see in your PC, the path is : C:\Users\Public\Pictures\Sample Pictures

Selected file name is : Chrysanthemum.jpg
Image Dimensions : 1024 x 768 , Image Size : 858 KB

Chrysanthemum


Image 2 : In this image, you see

Selected file name is : Chrysanthemum.jpg
Convert / Change Width : 400
Convert / Change Height : 400
Output File Name (Save with Different) : MyNewImage (.jpg) jpg extension predefined in coding.

Output

Image3 : See the output:

Output

Image4 : In this image, you can see:

Chrysanthemum.jpg
Image Dimensions : 1024 x 768 , Image Size : 858 KB

now coverted into,

MyNewImage.jpg
Image Dimensions : 400 x 400 , Image Size : 129 KB

coverted

ImageResize.aspx
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="ImageResize.aspx.cs" Inherits="ImageResize" %>  
  2.   
  3. <!DOCTYPE html>  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title></title>  
  8. </head>  
  9. <body>  
  10.     <form id="form1" runat="server">  
  11.     <div>  
  12.       
  13.         <br />  
  14.         <br />  
  15.         <br />  
  16.         <br />  
  17.         <asp:FileUpload ID="fuImage" runat="server" />  
  18.         <br />  
  19.         <br />  
  20.         Width :<asp:TextBox ID="txtWidth" runat="server"></asp:TextBox>  
  21.         <br />  
  22.         <br />  
  23.         Height :<asp:TextBox ID="txtHeight" runat="server"></asp:TextBox>  
  24.         <br />  
  25.         <br />  
  26.         Output File Name :<asp:TextBox ID="txtOutputFileName" runat="server"></asp:TextBox>  
  27.         <asp:Button ID="btnSubmit" runat="server" Text="Upload" OnClick="btnSubmit_Click" />  
  28.       
  29.     </div>  
  30.     </form>  
  31. </body>  
  32. </html>  
ImageResize.aspx.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.UI;  
  7. using System.Web.UI.WebControls;  
  8. using ImagerLib;  
  9.   
  10. public partial class ImageResize : System.Web.UI.Page  
  11. {  
  12.     protected void Page_Load(object sender, EventArgs e)  
  13.     {  
  14.   
  15.     }  
  16.     protected void btnSubmit_Click(object sender, EventArgs e)  
  17.     {  
  18.         string filename = Path.GetFileName(fuImage.PostedFile.FileName);  
  19.         //string str = DateTime.Now.ToString("hhmmssffffff") + filename;  
  20.         string str = filename;  
  21.         fuImage.SaveAs(Server.MapPath("ImgDir/" + str));  
  22.         string imgPath = "D:\\RND_Project\\ImageResize\\ImgDir\\";  
  23.           
  24.         Imager.PerformImageResizeAndPutOnCanvas(imgPath,filename, Convert.ToInt16(txtWidth.Text), Convert.ToInt16(txtHeight.Text), txtOutputFileName.Text.ToString()+".jpg");  
  25.   
  26.     }  

Up Next
    Ebook Download
    View all
    Learn
    View all