cookieChoices = {};

Friday 20 September 2013

How to resize image in Asp.net?

Description: While working on asp.net application it is sometimes required to resize the image as per application requirement. Suppose there is image upload functionality in your website where user can upload their pictures. In this case you must resize the image before storing so that web space requirement for storing can be reduced.

Implementation: Let's understand by creating a demo website.

Source Code:
  • In the design page (.aspx) place a FileUpload Control and a Button control as:
<table>
        <tr>
                <td>
                    <asp:FileUpload ID="FileUpload1" runat="server" />
                </td>
            </tr>
            <tr>
                <td>
                      <asp:Button ID="btnUpload" runat="server" Text="Submit"
            onclick="btnUpload_Click" /></td>
         </tr>          
  </table>

C#.NET Code to  upload and resize the images
  • In the code behind file (.aspx.cs) write the code as:
First include following namespaces:

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Design;
using System.IO;
  • Then write the code as:
protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            string img=string.Empty;
            Bitmap bmpImg=null;
            try
            {
                bmpImg = Resize_Image(FileUpload1.PostedFile.InputStream, 210, 130);
                img = Server.MapPath("images/") + Guid.NewGuid().ToString() + “.png";
                bmpImg.Save(img, ImageFormat.Jpeg);
            }
            catch (Exception ex)
            {
                Response.Write("Error occured: " + ex.Message.ToString());
            }
            finally
            {
                img = string.Empty;
                bmpImg.Dispose();
            }      
          }
    }
  

private Bitmap Resize_Image(Stream streamImage, int maxWidth, int maxHeight)
    {
        Bitmap originalImage = new Bitmap(streamImage);
        int newWidth = originalImage.Width;
        int newHeight = originalImage.Height;
        double aspectRatio = Convert.ToDouble(originalImage.Width) /Convert.ToDouble(originalImage.Height);

        if (aspectRatio <= 1 && originalImage.Width > maxWidth)
        {
            newWidth = maxWidth;
            newHeight = Convert.ToInt32(Math.Round(newWidth / aspectRatio));
        }
        else if (aspectRatio > 1 && originalImage.Height > maxHeight)
        {
            newHeight = maxHeight;
            newWidth = Convert.ToInt32(Math.Round(newHeight * aspectRatio));
        }
        return new Bitmap(originalImage, newWidth, newHeight);
    }

1 comment:

  1. Superbly written article, if only all bloggers offered the same content as you, the internet would be a far better place..
    java代写

    ReplyDelete