Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

Asp.net Create/generate thumbnails from images

May 2, 2011
Introduction

Here I will explain how to generate thumbnails dynamically from uploaded images and how to bind thumbnails to datalist using asp.net.

Description:

In previous post I explained clearly how to bind images from folder to datalist . Now I will explain how to generate thumbnails from uploaded images and how to bind those thumbnails to datalist using asp.net. In website development sometimes we get requirement like generating thumbnails from images without losing quality of image and it’s same like original image. For that first create one new website after that right click on that website select New Folder give name as Images because here I am using same name if you want to use another name you need to change the name in code also. After completion of adding Images folder to your website Design your aspx page like this 


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Generate a Thumbnails from Uploaded Image</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<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", "~/Images/{0}") %>' runat="server" />
<br />
<asp:HyperLink ID="HyperLink1" Text='<%# Bind("Name") %>' NavigateUrl='<%# Bind("Name", "~/Images/{0}") %>' runat="server"/>
</ItemTemplate>
<ItemStyle BorderColor="Brown" BorderStyle="dotted" BorderWidth="3px" HorizontalAlign="Center"
VerticalAlign="Bottom" />
</asp:DataList>
</div>
</form>
</body>
</html>
After that add following namespaces in code behind

using System.Collections;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
After completion of adding namespaces write the following code


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDataList();
}
}
protected void BindDataList()
{
DirectoryInfo dir = new DirectoryInfo(MapPath("Images"));
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("Images/" + filename);
Stream strm = fileupload1.PostedFile.InputStream;
var targetFile = targetPath;
//Based on scalefactor image size will vary
GenerateThumbnails(0.07, strm, targetFile);
BindDataList();
}
private void GenerateThumbnails(double scaleFactor, Stream sourcePath, string targetPath)
{
using (var image = Image.FromStream(sourcePath))
{
var newWidth = (int)(image.Width * scaleFactor);
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);
}
}
Demo


Download sample code attached

If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

28 comments :

Farheen said...

Your website is awesome...
I learnt to do so many wonderful things, which i couldn't, even after searching on the web for weeks...
I just wish I had found your site months back..
I'm building an image editor website for final year college project, and I've found your site very very helpful..
Thank you...
Farheen

Suresh Dasari said...

thanks farheen keep visiting................

Shashank said...

when we upload a image in folder then we find this type of error

CS0246: The type or namespace name 'var' could not be found (are you missing a using directive or an assembly reference?)

Shashank said...

And my problem is this if we want upload an image and its path will store in databse and i have three folders like "Original","Thumble" and "Normal" so uploades image is also store in three category depends on the client. plz give me a answer..........

Dheeraj said...

This is really awesome. I was searching for this since long, finally my search ends here and I just want to know why Ajax Toolkit extender controls doesn't work in update panel.
Thanks in Advance :)

Navjot Singh said...

thanks for this post.
This is such which i was searching on the web.

aksh said...

i got error GenerateThumbnails() function that var need some namespace reference?

Pankaj said...

hey m creating a website for online mobile recharging, for that i need to detect service operator ,State, automatically when user enter the mobile number

Please help me

Unknown said...

im not using the exact thing. im just displaying files and folders just like web album. I want these thumbnails to appear for pictures. I am having issues while syncing the above code with Imange button. How to add this code so that it works for imageurl

Shaik Shameer ali said...

Hi suresh,

can you please help me in creating a thumbnail from a uploaded video into the server..
the video format will be in .flv format & I should capture the thumbnail(image frame) of the video which was uploaded..

I am working with asp.net & c#...
can you please help me with the coding...

thanks
shameer ali..

Anonymous said...

Your website is Awesome .
please give more example of Web services and wcf
thats are valuable us .

vignesh said...

using (var image = Image.FromStream(sourcePath))

i got error in this sir y it will come can u send

Unknown said...

Thanks bro For your Code... I have one problem thumbnails generated are too small compared to your thumbnail images which are already existing...
how to increase the size.

Holly Quinn said...

Is there a way to make the larger image available. Like say when you click on the thumbnail they are taken to a page with the larger image?

parthi said...

Hi suresh

I have a problem when means

using (var image = Image.FromStream(sourcePath))

in this line i got parameter is not valid

because i use i add some string before the file upload chareacters
i got error like this will you pls help me...

Anonymous said...

Thanks for Ur website...I want to extend my present gallery set up
.
I doing a builder website. Each Project has gallery.

http://www.tbpl.in/tbplanjaligardens-gallery.aspx . Now all photos under one project is bind to ONE datalist...

I want Gallery as time line.. Based on inserted date, Photos are under one album...Last inserted album should come Top. HOW TO DO THIS...

PRESENTlY i USING ONE DATALIST(STATIC) ,all photos under one project is bind to this...

Anonymous said...

hiiii.........sir!!!
can u help me in my .net project
i wants to the alternate name to the images....but i can't..................i gave simply some name to the "alt" atribute but it doesn't implement wht i except...............so plzzz can u help me....plzzzzzzzzzzzzzzzzzzzzzzz...reply fast

jasveer said...

hiiii.........sir!!!
can u help me in my .net project
i wants to the alternate name to the images....but i can't..................i gave simply some name to the "alt" atribute but it doesn't implement wht i except...............so plzzz can u help me....plzzzzzzzzzzzzzzzzzzzzzzz...reply fast

jasvir mrahar said...

hiiii.........sir!!!
can u help me in my .net project
i wants to gave the alternate name to the images....but i can't..................i gave simply some name to the "alt" atribute but it doesn't implement wht i expect...............so plzzz can u help me....plzzzzzzzzzzzzzzzzzzzzzzz...reply fast

Unknown said...

Hello Sir,

Your Article is good i tried it,

I am facing an error while saving the thubmnail

A generic error occurred in GDI+.

Anonymous said...

Hello Sir..

Thanks for ur Code...

I am facing an error while saving the thubmnail

Error : "A generic error occurred in GDI+."

Any Solution ??Please help ASAP

Anonymous said...

Hello Sir..

Thanks for ur Code...

I am facing an error while saving the thubmnail

Error : "A generic error occurred in GDI+."

Any Solution ??Please help ASAP

Unknown said...

Suresh,

Your site is the Final Destination..! I visit and look for something in the web after a day or 2 days of searching ..finally I visit your site and find solution.I decided to search first in your site and then google.

Anonymous said...

I am also get the error """A generic error occurred in GDI+. """""""""
Please Help me.......................

Unknown said...

Suresh sir some for you tutorils output image was nit display..properly

Anonymous said...

hi suresh,
i got error "A generic error occurred in GDI+."
please help

Unknown said...

hi suresh
a small clarification required in source file we are mentioning as '<%# Bind("Name", "~/Images/{0}") %>' images folder but my purpose is to pick files from images folder + project subdirectory
like images + DropDownlist1.text where dropdown list contains project name on text change event thumbnails should get refresh

Anonymous said...

how to reduce the images size to 100 to 200 kb ..???
Please help me

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.