Advertisements
Home > DotNet > How to create thumbnail image in ASP.Net/C# OR resize the image before upload in ASP.Net/C#

How to create thumbnail image in ASP.Net/C# OR resize the image before upload in ASP.Net/C#


How to reduce the size of image before uploaded to the server in ASP.Net/C#

In most of the ASP.Net application with uploaded image facility will face the performance issue while loading uploaded images to display for the user. We can limited the maximum size of the image that a user can upload but it may not be a good solution because a user has to facing very difficult situation for uploading a large image. He has to reduce the image from other tools and upload again.

The better approach to solve this issue, we are not going to giving any maximum size limit for uploading image. Instead we are internally reducing the size of the image that a user going to upload by checking whether it is exceeds affordable size.  Then there is no constraints are given to user so that he doesn’t care about the size and quality of the image.

Image Size 764 KB

Simple steps to reduce the size of image before upload in ASP.Net/C#

 Here we are going to demonstrate a very simple and best approach to reduce the size of the image before uploaded to the server. In some application we need to show thumbnail image with uploaded images. In that case there is no need to store very large image in the server. So before going to uploading to the server, we are going to create thumbnail image or reduce the size of image as we wish using C#/ASP.net. This is very simple sample of reducing image and can be easily understand by beginners also.

Step by Step process to create an application for reducing size of image before uploaded to the server in ASP.Net/C#

 Step 1 . Create a ASP.Net project and create a web page.

Step 2.  Drag a file uploader, button and Datalist(for display uploaded images)

ASPX Page

 <asp:Panel runat="server">
<asp:FileUpload ID="fileupload1" runat="server" />
<asp:Button ID="btnsave" runat="server" Text="Upload" OnClick="btnsave_Click" />
</div>
<div>
<asp:DataList ID="dtlist" runat="server" RepeatColumns="3" CellPadding="5">
<ItemTemplate>
<asp:Image ID="Image1" ImageUrl='<%# Bind("Name", "~/Images1/{0}") %>' runat="server" />
<br />
<asp:HyperLink ID="HyperLink1" Text='<%# Bind("Name") %>'
NavigateUrl='<%# Bind("Name", "~/Images1/{0}") %>'
runat="server" />
</ItemTemplate>
<ItemStyle BorderColor="Brown" BorderStyle="dotted" BorderWidth="3px"
HorizontalAlign="Center"
VerticalAlign="Bottom" />
</asp:DataList>
</asp:Panel>

 

Step 3 .  In page load call function ‘BindDataList’ to display uploaded images

Step 4.   On Save button click event, call function ‘GenerateThumbnails’ for reduce of image.

Code Behind Page 

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDataList();
}
}
protected void BindDataList()
{
DirectoryInfo dir = new DirectoryInfo(MapPath("Images1"));
FileInfo[] files = dir.GetFiles();
ArrayList listItems = new ArrayList();
foreach (FileInfo info in files)
{
listItems.Add(info);
}
dtlist.DataSource = listItems;
dtlist.DataBind();
}
protected void btnsave_Click(object sender, EventArgs e)
{
string filename = Path.GetFileName(fileupload1.PostedFile.FileName);
string targetPath = Server.MapPath("Images1/" + filename);
Stream strm = fileupload1.PostedFile.InputStream;
var targetFile = targetPath;
//Based on scalefactor image size will vary
GenerateThumbnails(0.5, strm, targetFile);
BindDataList();
}
private void GenerateThumbnails(double scaleFactor, Stream sourcePath,
string targetPath)
{
using (var image = Image.FromStream(sourcePath))
{
// can given width of image as we want
var newWidth = (int)(image.Width * scaleFactor); 
// can given height of image as we want
var newHeight = (int)(image.Height * scaleFactor);
var thumbnailImg = new Bitmap(newWidth, newHeight);
var thumbGraph = Graphics.FromImage(thumbnailImg);
thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
thumbGraph.DrawImage(image, imageRectangle);
thumbnailImg.Save(targetPath, image.RawFormat);
}           
}
 

Image Size 36 KB

By using above application, we can reduce the size of images before uploaded to the server. If we check the size of the image that we uploaded, that will be less than the size of image that having in the local folder. We can implement this mechanism in most of the shopping site and photo gallery sites so that we can store large amount of images with small size and it will help the performance of the application. We can identify that even reducing the size of image there is no variation in quality or clarity of the image.  So we can easily reduce the resolution of the image using above code in ASP.Net/C# application.

Advertisements
  1. October 16, 2011 at 8:33 pm

    Make sure you wrap ‘thumbGraph’ and ‘thumbnailImg’ in using clauses – right now they are leaking memory and GDI handles (.NET does not GC System.Drawing objects properly).

    It’s also better to set specific target sizes for images rather than simply making each image 1/2 its original size (what if it is 300×300 or 3000×3000)?

    You should also specify the jpeg encoding quality – 90 is better than 100, strangely enough.
    See http://nathanaeljones.com/163/20-image-resizing-pitfalls/ for 30 tips on doing image resizing properly.

  2. November 9, 2011 at 5:06 pm

    ujhuy,jk.,kjl.lk.l.

  3. Abdhesh Mishra
    November 21, 2011 at 6:09 am

    Hi,

    i need to help.

    i have using jquery plugin for multiple image upload in asp.net. but i need help for how we can image resize in c#.net or jquery.

    please help me .

    Thanks & Regards

    Abdhesh Mishra
    9999208994

  4. November 30, 2011 at 4:20 am

    We can implement the same code in your scenario. If you need code snippet or more help please post your email id with clear requirement.

  5. December 3, 2011 at 6:39 am

    Thanks this post help me a lot

  6. jay
    December 3, 2011 at 11:06 am

    hi
    when i tried to execute this it gave me this error..
    “A generic error occurred in GDI+”

    pls let mw knw ..

  7. Chandan
    January 13, 2012 at 12:55 pm

    hi
    when i tried to execute this it gave me this error..
    “A generic error occurred in GDI+”

    I am using windows application asp.net+c#

    Please help me………..

  8. hsr
    January 24, 2012 at 5:26 pm

    this code is helpful for me for uploading resize(small size) of image/

  9. Vijaykumar
    January 25, 2012 at 1:09 pm

    how to implement thumbnail in my asp.net.Help me

  10. bhuvana
    August 6, 2012 at 11:26 am

    jay :
    hi
    when i tried to execute this it gave me this error..
    “A generic error occurred in GDI+”
    pls let mw knw ..

  11. August 6, 2012 at 12:41 pm

    Hi bhuvana,
    You have include following packages on the top of cs page.
    Please try it let me know the result.
    using SD = System.Drawing;
    using System.Drawing.Drawing2D;

  12. August 17, 2012 at 5:42 pm

    jay :
    hi
    when i tried to execute this it gave me this error..
    “A generic error occurred in GDI+”
    pls let mw knw ..

    bhuvana :

    jay :
    hi
    when i tried to execute this it gave me this error..
    “A generic error occurred in GDI+”
    pls let mw knw ..

    bhuvana :

    jay :
    hi
    when i tried to execute this it gave me this error..
    “A generic error occurred in GDI+”
    pls let mw knw ..

    tuvian :
    Hi bhuvana,
    You have include following packages on the top of cs page.
    Please try it let me know the result.
    using SD = System.Drawing;
    using System.Drawing.Drawing2D;

    The error may be cause of file permission, set wrx to the folder

  13. August 17, 2012 at 5:46 pm

    “A generic error occurred in GDI+”
    The error may be cause due to file permission, set wrx to the folder, file permission will solve

  14. August 17, 2012 at 5:51 pm

    This is also one another way i accomplish same task:

    public static System.Drawing.Image ScaleImage(System.Drawing.Image image, int maxHeight)
    {
    var ratio = (double)maxHeight / image.Height;

    var newWidth = (int)(image.Width * ratio);
    var newHeight = (int)(image.Height * ratio);

    var newImage = new Bitmap(newWidth, newHeight);
    using (var g = Graphics.FromImage(newImage))
    {
    g.DrawImage(image, 0, 0, newWidth, newHeight);
    }
    return newImage;
    }

    This will return image with the given ratio, call this function while uploading something like this:
    System.Drawing.Bitmap bmpPostedImage = new System.Drawing.Bitmap(File1.PostedFile.InputStream);
    System.Drawing.Image objImage = ScaleImage(bmpPostedImage, 81);
    objImage.Save(SaveLocation,ImageFormat.Png);
    lblmsg.Text = “The file has been uploaded.”;

    In Detail : http://satindersinght.blogspot.in/2012/08/how-to-resize-image-while-uploading-in.html

  15. May 9, 2013 at 9:59 am

    it is a good way to creat thumnail in C#, this is my codes in creating thumnail
    public int CreateThumbnail(int ImageID, int Width, int Height);

  16. December 31, 2013 at 3:11 am

    Hi there, I want to subscribe for this web site to
    get newest updates, so where can i do it please help.

  17. January 2, 2014 at 10:48 am

    Please fill your email id on right top most space provided for Email subscription.

  1. May 22, 2012 at 9:09 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: