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. |
|||
|
|||
28 comments :
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
thanks farheen keep visiting................
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?)
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..........
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 :)
thanks for this post.
This is such which i was searching on the web.
i got error GenerateThumbnails() function that var need some namespace reference?
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
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
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..
Your website is Awesome .
please give more example of Web services and wcf
thats are valuable us .
using (var image = Image.FromStream(sourcePath))
i got error in this sir y it will come can u send
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.
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?
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...
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...
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
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
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
Hello Sir,
Your Article is good i tried it,
I am facing an error while saving the thubmnail
A generic error occurred in GDI+.
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
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
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.
I am also get the error """A generic error occurred in GDI+. """""""""
Please Help me.......................
Suresh sir some for you tutorils output image was nit display..properly
hi suresh,
i got error "A generic error occurred in GDI+."
please help
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
how to reduce the images size to 100 to 200 kb ..???
Please help me
Note: Only a member of this blog may post a comment.