In this article, you will come to know about the followings things:
- File Upload
- 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:
- System.Drawing.Configuration.
- System.Drawing.Design.
- System.Drawing.Drawing2D
- System.Drawing.Imaging
- System.Drawing.Printing
- 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
- protected void btnSubmit_Click(object sender, EventArgs e)
- {
- string filename = Path.GetFileName(fuImage.PostedFile.FileName);
-
- string str = filename;
- fuImage.SaveAs(Server.MapPath("ImgDir/" + str));
- string imgPath = "D:\\RND_Project\\ImageResize\\ImgDir\\";
-
- Imager.PerformImageResizeAndPutOnCanvas(imgPath,filename, Convert.ToInt16(txtWidth.Text), Convert.ToInt16(txtHeight.Text), txtOutputFileName.Text.ToString()+".jpg");
-
- }
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
- public static void PerformImageResizeAndPutOnCanvas(string pFilePath, string pFileName, int pWidth, int pHeight,string pOutputFileName )
- {
-
- System.Drawing.Image imgBef;
- imgBef = System.Drawing.Image.FromFile(pFilePath + pFileName);
-
-
- System.Drawing.Image _imgR;
- _imgR = Imager.Resize(imgBef, pWidth, pHeight, true);
-
-
- System.Drawing.Image _img2;
- _img2 = Imager.PutOnCanvas(_imgR, pWidth, pHeight, System.Drawing.Color.White);
-
-
- SaveJpeg(pFilePath + pOutputFileName, _img2);
-
- }
As you must have seen, above:
- First, I had called FromFile method of System.Drawing.Image, which coverts an uploaded file into System.Drawing.Image.
- Resize function of Imager.cs resizes the image. There is a last boolean parameter, which conditionally works (only Resize If Wider).
- PutOnCanvas function of Imager.cs puts the image on virtually created canvas for an image.
- SaveJpeg is a last method to be called to save the file in JPEG format.
Imager.cs
- using System;
- using System.Drawing;
- using System.Drawing.Drawing2D;
- using System.Drawing.Imaging;
- using System.IO;
- using System.Linq;
- using System.Web;
-
- namespace ImagerLib
- {
- public static class Imager
- {
-
-
-
-
-
- public static void SaveJpeg(string path, Image img)
- {
- var qualityParam = new EncoderParameter(Encoder.Quality, 100L);
- var jpegCodec = GetEncoderInfo("image/jpeg");
-
- var encoderParams = new EncoderParameters(1);
- encoderParams.Param[0] = qualityParam;
- img.Save(path, jpegCodec, encoderParams);
- }
-
-
-
-
-
-
-
- public static void Save(string path, Image img, ImageCodecInfo imageCodecInfo)
- {
- var qualityParam = new EncoderParameter(Encoder.Quality, 100L);
-
- var encoderParams = new EncoderParameters(1);
- encoderParams.Param[0] = qualityParam;
- img.Save(path, imageCodecInfo, encoderParams);
- }
-
-
-
-
-
-
- public static ImageCodecInfo GetEncoderInfo(string mimeType)
- {
- return ImageCodecInfo.GetImageEncoders().FirstOrDefault(t => t.MimeType == mimeType);
- }
-
-
-
-
-
-
-
-
-
- public static Image PutOnCanvas(Image image, int width, int height, Color canvasColor)
- {
- var res = new Bitmap(width, height);
- using (var g = Graphics.FromImage(res))
- {
- g.Clear(canvasColor);
- var x = (width - image.Width) / 2;
- var y = (height - image.Height) / 2;
- g.DrawImageUnscaled(image, x, y, image.Width, image.Height);
- }
-
- return res;
- }
-
-
-
-
-
-
-
-
- public static Image PutOnWhiteCanvas(Image image, int width, int height)
- {
- return PutOnCanvas(image, width, height, Color.White);
- }
-
-
-
-
-
-
-
-
-
- public static Image Resize(Image image, int newWidth, int maxHeight, bool onlyResizeIfWider)
- {
- if (onlyResizeIfWider && image.Width <= newWidth) newWidth = image.Width;
-
- var newHeight = image.Height * newWidth / image.Width;
- if (newHeight > maxHeight)
- {
-
- newWidth = image.Width * maxHeight / image.Height;
- newHeight = maxHeight;
- }
-
- var res = new Bitmap(newWidth, newHeight);
-
- using (var graphic = Graphics.FromImage(res))
- {
- graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
- graphic.SmoothingMode = SmoothingMode.HighQuality;
- graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
- graphic.CompositingQuality = CompositingQuality.HighQuality;
- graphic.DrawImage(image, 0, 0, newWidth, newHeight);
- }
-
- return res;
- }
-
-
-
-
-
-
-
- public static Image Crop(Image img, Rectangle cropArea)
- {
- var bmpImage = new Bitmap(img);
- var bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);
- return bmpCrop;
- }
-
- public static byte[] imageToByteArray(System.Drawing.Image imageIn)
- {
- MemoryStream ms = new MemoryStream();
- imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
- return ms.ToArray();
- }
-
- public static Image byteArrayToImage(byte[] byteArrayIn)
- {
- MemoryStream ms = new MemoryStream(byteArrayIn);
- Image returnImage = Image.FromStream(ms);
- return returnImage;
- }
-
-
- public static string GetImage(object img)
- {
- return "data:image/jpg;base64," + Convert.ToBase64String((byte[])img);
- }
-
-
- public static void PerformImageResizeAndPutOnCanvas(string pFilePath, string pFileName, int pWidth, int pHeight,string pOutputFileName )
- {
-
- System.Drawing.Image imgBef;
- imgBef = System.Drawing.Image.FromFile(pFilePath + pFileName);
-
-
- System.Drawing.Image _imgR;
- _imgR = Imager.Resize(imgBef, pWidth, pHeight, true);
-
-
- System.Drawing.Image _img2;
- _img2 = Imager.PutOnCanvas(_imgR, pWidth, pHeight, System.Drawing.Color.White);
-
-
- Imager.SaveJpeg(pFilePath + pOutputFileName, _img2);
-
- }
- }
- }
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
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.
Image3 : See the 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
ImageResize.aspx
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="ImageResize.aspx.cs" Inherits="ImageResize" %>
-
- <!DOCTYPE html>
-
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title></title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
-
- <br />
- <br />
- <br />
- <br />
- <asp:FileUpload ID="fuImage" runat="server" />
- <br />
- <br />
- Width :<asp:TextBox ID="txtWidth" runat="server"></asp:TextBox>
- <br />
- <br />
- Height :<asp:TextBox ID="txtHeight" runat="server"></asp:TextBox>
- <br />
- <br />
- Output File Name :<asp:TextBox ID="txtOutputFileName" runat="server"></asp:TextBox>
- <asp:Button ID="btnSubmit" runat="server" Text="Upload" OnClick="btnSubmit_Click" />
-
- </div>
- </form>
- </body>
- </html>
ImageResize.aspx.cs
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using ImagerLib;
-
- public partial class ImageResize : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
-
- }
- protected void btnSubmit_Click(object sender, EventArgs e)
- {
- string filename = Path.GetFileName(fuImage.PostedFile.FileName);
-
- string str = filename;
- fuImage.SaveAs(Server.MapPath("ImgDir/" + str));
- string imgPath = "D:\\RND_Project\\ImageResize\\ImgDir\\";
-
- Imager.PerformImageResizeAndPutOnCanvas(imgPath,filename, Convert.ToInt16(txtWidth.Text), Convert.ToInt16(txtHeight.Text), txtOutputFileName.Text.ToString()+".jpg");
-
- }
- }