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

how to resize image without losing image quality or how to reduce image file size without losing quality using asp.net

May 3, 2011
Introduction

Here I will explain how to resize an image without losing any quality from uploaded images using asp.net.

Description:

In previous post I explained clearly how to generate the thumbnails dynamically. Here I am using same concept to resize the image without losing quality just by changing scaling factor in previous post. In social networking sites after upload images they will reduce the size of the photo but the quality will be same after seen that I tried to write this post. I taken one of my pic that pic size is 3.62 MB before resize Image that is here 


Now I am trying to resize above 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.5, 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);
}
}

After completion of above run your application and upload one image and check the size of image after resize and before resize you will find huge difference in size but quality will be same as original one.

After run my application I upload above pic to resize after completion process my pic size reduces drastically to 218 KB do you believe this but it’s true we can reduce image size as much as possible by using above code without losing quality of image and my image quality same as original one check it


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

73 comments :

Anonymous said...

how to do it without fileupload ? i mean i want to resize an specified image, then i am getting stream error, please help

Suresh Dasari said...

Hi ,
i think that error because of your not passing correct image path that's why your getting that error. Here i am passing the imagepath by using the upload control. Please check your image whether your passing correct value or not

Anonymous said...

i am passing correct value but i am getting problem because i have path in a string, i need to convert this string into inputstream or stream and i tried with several way but its still error just because of stream, please help
can you provide code to my email id ?

copland.adam@yahoo.com

Anonymous said...

Awesome!!!!Thanks a ton!!!You solved a weeks hunt for the code!!!!

Anonymous said...

Image.FromStream doesn't exist? Can you help me out with this?

chvenkat said...

Image class present in two namespaces 'System.Web.UI.WebControls' and 'System.Drawing'.That's why you are getting Image.FromStream doesn't exist. To solve this write System.Drawing.Image.FromStream.

Anonymous said...

thanks alot for such nice task,cud u plz tell me that how could i create a thumnail for a video...my task is i just want to show something(thumbnail or screenshot) of the uploaded video on server(not from youtube,vimeo url)??

Anonymous said...

how about change image sizeand maintian same height and width to display it again with old width and heigh and new size

Anonymous said...

Thank You...

Anonymous said...

This is nice code , But I found it checks each image before uploading. For example if we are uploading image in Demo folder and demo folder contains 90 images. Your code checks 90 times and then load image . How this work if we are having a lot of images in server???? Please sort this
kumawat.ban@gmail.com

Anonymous said...

Nice code !!

w3services.net

Anonymous said...

Image.FromStream doesn't exist? please resolve this error.

Shahab Ashraf said...

replace Image.FromStream to System.Drawing.Image.FromStream to remove the Stream error.
I got it.
Thanks for this post.

sumesh said...
This comment has been removed by the author.
Aniruddha said...

I'm facing this error..A generic error occurred in GDI+

Unknown said...

need help urgently i have created a gallery in asp.net in which images are retrieving from database n have used listview control to call them now i have 2 enlarge the images on mouseover buh failed to do so..

Anonymous said...

When we upload images with size more than 4mb then it doesn't work..

Pratibha said...

nice code....thanks....

sunny said...

thanks and keep it up
u r helping a lot of peoples

sunny said...

anonymous, my friend
use this to upload images more than 4mb.
"

"

put this code in your web.config file in tag

sunny said...

httpRuntime executionTimeout="9999" maxRequestLength="2097151"/

sunny said...

system.web

jatin said...

hi suresh.....
hey, i am crating a small website...
and i have to create a chat application in my project, bt cant create it,
i had find many ways bt i cant success,
but if have any solution then send me plz.....

Anonymous said...

thanku bhai

Anonymous said...

thanku bhai
kmt

Anonymous said...

A generic error occurred in GDI+.

Code working on local system but once uploaded to shared hosting server its giving error please help me

Unknown said...
This comment has been removed by the author.
Anonymous said...

I'm facing this error..A generic error occurred in GDI+

Answer : Give Read & Write Permission on folder which u upload image.

Unknown said...

very nice code thanks

Anonymous said...

Code does not work for image size more than 4 mb.

Anonymous said...

I'm facing this error..A generic error occurred in GDI+

Kettavan said...

Nice code...

Nagesh Chowdary Manukonda said...

Its very Nice Thanks.

Anonymous said...

Awesome

very good!!!!!

Anonymous said...

superb code thank you so much..

Unknown said...

I'm facing this error..A generic error occurred in GDI+

Answer : use different path for saving source and destnation

Dhiraj said...
This comment has been removed by the author.
Anonymous said...

hello suresh

i want to change the size of the image during run time like we have a functionality like zoom in zoom out some like that so please help me out how this thing can be possible

Anonymous said...

Good article

Anonymous said...

great solution, I appreciate that suresh, keep it up..

Unknown said...

if i want to multiple images than???

MaheshDhiman said...

Picture quality not appearing best with your code

Unknown said...

hi all.. can anybody help me how to crop the image and reduce the size and dimension of an image

Unknown said...

hey hi....i am using a image handler for uploading image and i also want to reduce the size of my image..but in my handler it takes image as input stream...so how can i pass the stream from that resized Image..??

Unknown said...

Thank-you very much this is working fine....

Unknown said...

Hello Suresh,

I used your method "GenerateThumbnails" for resizing my image and its working well for single file but when it comes for multiple file then its firing error.

In my scenario,
I have two file uploaders for image-
One for main image
another for uploading multiple image - (using jquery.MultiFile.js)

Now when I run one by one then its working well for me
but when I run togather its firing error saying that "Parameter is not valid" in memory stream.

Single image is uploading fine for me but when control goes for multiple image uploader (HttpFileCollection hfc = Request.Files; - in my code) then its firing error from this
line - "using (var image = Image.FromStream(sourcePath))" - "Parameter is not valid"

I need help in this, please help me.
Thanks in advance.

Unknown said...
This comment has been removed by the author.
Unknown said...
This comment has been removed by the author.
Unknown said...

You are great Genius in beginner programmer

Santosh Pal said...

i am also passing correct value but i am getting problem because i have path in a string, i need to convert this string into inputstream and i tried with several way but its still error just because of stream, please help
can you provide code to my email id ?

santoshpal.0504@gmail.com.com

Anonymous said...

Very Good Coding For Software Developers,I am Self Learner In Asp.net, So,This Article Very Useful To Me

Thankyou

Unknown said...

Hi..your code is resizing all image type....now we are uploading some pic which are of 10kb or 40kb...it is trying to resize this image as well and hence images are getting corrupted....is it possible that it would first check the size of image and then will further go for compression...pls help

Anonymous said...

Thank bro.
It works like a charm.

Unknown said...
This comment has been removed by the author.
Unknown said...

I'm facing this error..A generic error occurred in GDI+.. Please help me...

Anonymous said...

thumbnailImg.Save(targetPath, image.RawFormat);

Here we have to add instead of targetpath to your own path like

thumbnailImg.Save(Server.MapPath(@"~\productimages\" + filepath), image.RawFormat);

Support for .NET Developers said...

a generic error occurred in gdi+.

khizer said...

i want to change only size of the image,i dont want to change width and height
is it possible?
for ex if my image is 200*230 and 200kb,i just want to change 200kb to 100kb or less with out loosing width and height
i used ur code its changing width and height also.

Sathish said...

Stream strm = fileupload1.PostedFile.InputStream; how can we change this line while using file path.

Sathish said...

pls mail me to test7use@gmail.com

Sathish PS said...

Stream fs = File.OpenRead(@"c:\testdocument.docx");
while using the path use like this it works.

Anonymous said...

your both image size are almost same only difference of 2-3 kb

Unknown said...

i have path in a string, i need to convert this string into inputstream or stream and i tried with several way but its still error just because of stream, please help
can you provide code to my email id ? ramesh.ms986@gmail.com Pl.

Unknown said...

Nice Code Thanks...

Full Stack Developer said...

Hi,
Can I save that image into database if it is possible then how

Unknown said...

sir, i want pixel scaling of the image without loosing its quality.Sir urgently i need your help.thank you!

Unknown said...
This comment has been removed by the author.
Unknown said...

Hello. I am using multiple file upload and I want to compress every uploaded file. But unfortunately, I am not able to do using your code. The issue what I am facing is GenerateThumbnails method is always taking 1st uploaded image and saving with other file names but what I need is saving multiple files with their own filenames.

On investigation, I found that fileupload.postedfile is holding 1st uploaded filename when processing 2nd compression which is held by System.Web.HttpInputStream in temporary files of ASP.NET.

Is there any way to clear that out before compressing 2nd image?

BCA Study Materials said...

its working awsome thnks for this code

princy said...
This comment has been removed by the author.
princy said...

I want to change colour of selected portion of an image and increase or decrease image width and length.
Please help me

Unknown said...

hi
your code working good for me but when i convert input stream in bytes in not able to convert so plz help for this issue.
thanks

Unknown said...

how to convert it back to its original size

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.