|
 |
Prize winner in Competition "ASP.NET Apr 2003"
|
|
|

Introduction
Uploading images & storing them dynamically after resizing is a painless affair now using .NET, unlike what it used to be in Classic ASP. There are several good articles on uploading & resizing images on CodeProject (.NET Image Uploading [^], File Upload with ASP.NET [^], Thumbnail Image Creation and Image format Conversion Utility [^]) & elsewhere on the net (True Image Resizing [^]). One issue with resizing images is that the quality of the image deteriorates. This article is written in praise of the PNG image format & shows how the original quality of the uploaded image of any regular format can be maintained & even be improved.
PNG - What's it?
Check out this excellent article on the PNG image format - FAQ: Converting GIF or JPG to PNG [^]. To paraphrase the article -
- PNG stands for Portable Network Graphics and pronounced "ping".
- PNG is supported by the major browsers (Microsoft IE and Netscape 4.x and higher)
- The images are a lot clearer, no more grainy GIF images or pixelated JPGs!
Source code
This application allows the user to set the dimensions for the image to be resized & uploaded. The resized image is converted into the W3C Portable Network Graphics (PNG) image format by using the PNG property of the ImageFormat class. <%@ Page Language="C#" %>
<%@ import Namespace="System.Drawing.Imaging" %>
<script runat="server">
void UploadBtn_Click(Object sender, EventArgs e)
{
String UploadedFile = MyFile.PostedFile.FileName;
int ExtractPos = UploadedFile.LastIndexOf("\\") + 1;
//to retrieve only Filename from the complete path
String UploadedFileName = UploadedFile.Substring
(ExtractPos,UploadedFile.Length - ExtractPos);
// Display information about posted file. Div is invisible by default
FileName.InnerHtml =UploadedFileName;
MyContentType.InnerHtml = MyFile.PostedFile.ContentType;
ContentLength.InnerHtml
= MyFile.PostedFile.ContentLength.ToString();
FileDetails.Visible = true; //div is made visible
// Save uploaded file to server at the in the Pics folder
MyFile.PostedFile.SaveAs(Request.PhysicalApplicationPath
+ "pics\\" + UploadedFileName );
//thumbnail creation starts
try
{
//Retrieve the image filename whose thumbnail has to be created
String imageUrl= UploadedFileName;
//Read in the width and height
int imageHeight =Convert.ToInt32(h.Text);
int imageWidth = Convert.ToInt32(w.Text);
//You may even specify a standard thumbnail size
//int imageWidth = 70;
//int imageHeight = 70;
if (imageUrl.IndexOf("/") >= 0 || imageUrl.IndexOf("\\") >= 0 )
{
//We found a / or \
Response.End();
}
//the uploaded image will be stored in the Pics folder.
//to get resize the image, the original image has to be
//accessed from the Pics folder
imageUrl = "pics/" + imageUrl;
System.Drawing.Image fullSizeImg
= System.Drawing.Image.FromFile(Server.MapPath(imageUrl));
System.Drawing.Image.GetThumbnailImageAbort dummyCallBack
= new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
System.Drawing.Image thumbNailImg
= fullSizeImg.GetThumbnailImage(imageWidth, imageHeight,
dummyCallBack, IntPtr.Zero);
//We need to create a unique filename for each generated image
DateTime MyDate = DateTime.Now;
String MyString = MyDate.ToString("ddMMyyhhmmss") + ".png" ;
//Save the thumbnail in PNG format.
//You may change it to a diff format with the ImageFormat property
thumbNailImg.Save ( Request.PhysicalApplicationPath
+ "pics\\" + MyString , ImageFormat.Png);
thumbNailImg.Dispose();
//Display the original & the newly generated thumbnail
Image1.AlternateText = "Original image";
Image1.ImageUrl="pics\\" + UploadedFileName;
Image2.AlternateText = "Thumbnail";
Image2.ImageUrl="pics\\" + MyString;
}
catch(Exception ex)
{
Response.Write("An error occurred - " + ex.ToString());
}
}
//this function is reqd for thumbnail creation
public bool ThumbnailCallback()
{
return false;
}
</script>
How to run the app
Unzip & run the .aspx file using IIS. Make sure a folder named PICS is created before-hand in the current working directory.
Conclusion
This article demonstrates how the quality of dynamically created images can be maintained & even enhanced by saving them in PNG format.
| You must Sign In to use this message board. |
|
| | Msgs 1 to 25 of 34 (Total in Forum: 34) (Refresh) | FirstPrevNext |
|
|
 |
|
|
hi , your sample so cool , but i have a question? how can i delete main image after resizing? cause when i wanna delete main image by : "system.io.file.delete(imgpath)" i recieve an error that file is used!??? how can i fix it? tanx
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
hi, this is a useful script and i'm trying to apply it but i need to complete it by recording path and image name on my db access.
how can i do?
please reply.
daniele
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Hi, i have a question/problem: when i create an Image object from a image file, into c#, how do i control the number of colors of its pallete? Meaning, i have a PNG 8bit depth 25colors that has 26KB, but when i send it to an C# image object its size duplicates.. and its now 52KB. How do i keep the same properties of the PNG for when i use, for example, a Image.save(...) it returns my original file ?
Thanks, Vitor
Vitor Duarte
|
| Sign In·View Thread·PermaLink | 2.00/5 (1 vote) |
|
|
|
 |
|
|
 |
|
|
How can I adjust the code to enable overwriting of files already uploaded. I have already changed the code to not auto assign a file name on each upload.
Thanks.
|
| Sign In·View Thread·PermaLink | 1.00/5 (1 vote) |
|
|
|
 |
|
|
The process cannot access the file "D:\test\pics\top.jpg" because it is being used by another process.
----------------------------------------------------------------------
FileDetails.Visible = true; //div is made visible // Save uploaded file to server at the in the Pics folder MyFile.PostedFile.SaveAs(Request.PhysicalApplicationPath + "pics\\" + UploadedFileName ); MyFile.Dispose();
|
| Sign In·View Thread·PermaLink | 1.00/5 (1 vote) |
|
|
|
 |
|
|
 |
|
|
ImageManipulator is a free open source image library I wrote up at Codeplex.
It deals with this issue by copying the image before making it available to work with. The assembly as well as a winforms demo app can be found at:
http://www.codeplex.com/imagemanipulator[^]
It would not be difficult to incorporate the png stuff from this article into that framework or vice-versa.
Project Description Assembly for easiest possible (1)resampling, with optional jpg compression (2)cropping, and (3)history stack (undo/redo)
- Gerry
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
I've found a problem applying this article on some images. The quality after the resizing is very poor. I've found an article that explain the work of GetThumbNailImage. Some kind of images have a thumbnail embedded inside (some kinf of camera save photo in this way) usually 32x32. When you call GetThumbNailImage to get the thumbnail, if is present the embedded thumbnail this method take the thumbnail and resize to the given width and height instead of resizing the fullsize image. This is the problem of loosing qaulity during the resizing: you have a 32x32 image resized to your desired size. My question is: how to determine if an image have an embedded thumbnail inside?
Edika
-- modified at 13:54 Sunday 26th February, 2006
|
| Sign In·View Thread·PermaLink | 2.00/5 (1 vote) |
|
|
|
 |
|
|
thx , u did a great job but i am asking why making dummy callBack especially it can works without it and we can just pass null to the function GetThumbnailImage instead of dummy call back Emad
[Message text goes here]
|
| Sign In·View Thread·PermaLink | 2.00/5 (2 votes) |
|
|
|
 |
|
|
The easiest way to upload and resize an image to the internet is I-Load. I-Load is a FREE ASP.NET web control with numerous benefits and features. You can download I-Load (it's FREE!) and view an online demo here:
http://www.radactive.com/en/Products/ILoad/Overview.aspx
|
| Sign In·View Thread·PermaLink | 1.00/5 (2 votes) |
|
|
|
 |
|
|
While this looks cool, unfortunately it ain't free - unless you just want to use it in demo mode!
Graham
|
| Sign In·View Thread·PermaLink | 1.50/5 (2 votes) |
|
|
|
 |
|
|
An error occurred - System.IO.FileNotFoundException: \\TEKKAMAN3\wwwroot$\fcfossombrone.it\cp\test\pics\conpng.png at System.Drawing.Image.FromFile(String filename, Boolean useEmbeddedColorManagement) at System.Drawing.Image.FromFile(String filename) at ASP.PNGUploader_aspx.UploadBtn_Click(Object sender, EventArgs e) in \\TEKKAMAN3\wwwroot$\fcfossombrone.it\cp\test\PNGUploader.aspx:line 52
|
| Sign In·View Thread·PermaLink | 2.00/5 (1 vote) |
|
|
|
 |
|
|
 Very good article to create thumbnail but to create images a bit larger it´s not so good, because the image lost the focus and quality.. If someone know a better solution, please post here..
Thanks
Gustavo R
|
| Sign In·View Thread·PermaLink | 3.25/5 (4 votes) |
|
|
|
 |
|
|
I tried to resize image and in due time found GetThumbnailImage method of bitmap object. However, there was a problem - resulting image was distorted. Then I found this article and tried to replicate "png" solution. I'm not sure why but it didn't work. After that I started anew and came up with Bitmap constructor solution. There is no need in changing file format. This function saves existing image file in a specified folder (see below). I tested it, and it works.
Public Function ImageResize(ByVal ph_folder_ As String, _ ByVal ph_new_folder_ As String, _ ByVal v_new_folder_ As String, _ ByVal file_name_ As String, _ ByVal name_add_ As String, _ ByVal width As Integer) As System.Web.UI.WebControls.Image Dim bm As New Bitmap(ph_folder_ + "\" + file_name_) Dim bmn As New Bitmap(Image.FromHbitmap(bm.GetHbitmap), width, CInt(Math.Round(width * (bm.Height / bm.Width), 0))) Dim img As System.Drawing.Image = Image.FromHbitmap(bmn.GetHbitmap) Try img.Save(ph_new_folder_ + "\" + Mid(file_name_, 1, InStrRev(file_name_, ".") - 1) + _ name_add_ + Mid(file_name_, InStrRev(file_name_, "."))) Dim img_new As New System.Web.UI.WebControls.Image() img_new.ImageUrl = v_new_folder_ + "/" + Mid(file_name_, 1, InStrRev(file_name_, ".") - 1) + _ name_add_ + Mid(file_name_, InStrRev(file_name_, ".")) Return img_new Catch ex As Exception _error = ex.Message Return Nothing End Try End Function
|
| Sign In·View Thread·PermaLink | 2.00/5 (3 votes) |
|
|
|
 |
|
|
this spraked my interest and as another viewer noted, the .net thumbnail thing doesn't work correctly with certian images. i have created a page that uploads the image and sizes it while keeping the proportions the same. here is the code, sub-optimal i'm sure.. but whatever... br />
<code><%@ Page Language="C#" %>
<%@ import namespace="System.IO" %> <%@ import Namespace="System.Drawing.Imaging" %> <%@ import Namespace="System.Drawing" %>
<script runat="server">
void Page_Load(Object sender, EventArgs e) {
}
void UploadBut_Click(Object sender, EventArgs args) { String FilePath = Request.PhysicalApplicationPath + "\\test\\"; String ImageName = "camp_2005"; Int32 ImageWidth = 190; Stream ImageStream = PhotoUpload.PostedFile.InputStream; if ( PhotoUpload.PostedFile.FileName != "") { SaveUploadImageAsJpeg(ImageStream, FilePath, ImageName, ImageWidth); SaveUploadImageAsGif(ImageStream, FilePath, ImageName, ImageWidth); SaveUploadImageAsPng(ImageStream, FilePath, ImageName, ImageWidth); } }
void SaveUploadImageAsJpeg(Stream ImageStream, String FilePath, String ImageName, Int32 ImageWidth) { String Extension = ".jpg"; String MimeType = "image/jpeg"; long Quality = 95; UploadImage(ImageStream, FilePath, ImageName, ImageWidth, Extension, MimeType, Quality); }
void SaveUploadImageAsGif(Stream ImageStream, String FilePath, String ImageName, Int32 ImageWidth) { String Extension = ".gif"; String MimeType = "image/gif"; long Quality = 100; UploadImage(ImageStream, FilePath, ImageName, ImageWidth, Extension, MimeType, Quality); }
void SaveUploadImageAsPng(Stream ImageStream, String FilePath, String ImageName, Int32 ImageWidth) { String Extension = ".png"; String MimeType = "image/png"; long Quality = 0; // has no effect on png files UploadImage(ImageStream, FilePath, ImageName, ImageWidth, Extension, MimeType, Quality); }
void UploadImage(Stream ImageStream, String FilePath, String ImageName, Int32 ImageWidth, String Extension, String MimeType, long Quality ) { try { System.Drawing.Image UploadedImage = System.Drawing.Image.FromStream(ImageStream); Int32 old_height = UploadedImage.Height; Int32 old_width = UploadedImage.Width; Int32 new_width = ImageWidth; Int32 new_height = (Int32) Math.Ceiling( (old_height * new_width)/old_width ); Bitmap smallerImg = new Bitmap(new_width, new_height); Graphics g = Graphics.FromImage(smallerImg); g.DrawImage(UploadedImage, 0, 0, new_width, new_height); UploadedImage.Dispose(); if ( !Extension.Equals(".png") ) { EncoderParameters myParams = new EncoderParameters(1); myParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Quality ); smallerImg.Save( FilePath + ImageName + Extension, GetEncoderInfo(MimeType), myParams); } else { smallerImg.Save( FilePath + ImageName + Extension , ImageFormat.Png); } smallerImg.Dispose(); } finally { } } private ImageCodecInfo GetEncoderInfo(string mimeType) { int j; ImageCodecInfo[] encoders; encoders = ImageCodecInfo.GetImageEncoders(); for(j = 0; j < encoders.Length; ++j) { if(encoders[j].MimeType == mimeType) { return encoders[j]; } } return null; }
// Validate the uploaded file is an image (.jpg, .jpeg, .gif) void ValidatePicture(Object src, ServerValidateEventArgs args) { args.IsValid = false; String fileName = PhotoUpload.PostedFile.FileName.ToLower(); if (fileName == "" || (fileName.IndexOf(".jpg") > -1) || (fileName.IndexOf(".jpeg") > -1) || (fileName.IndexOf(".gif") > -1)) args.IsValid = true; } </script>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html> <head> <title></title> </head>
<body> <form id="MainForm" enctype="multipart/form-data" runat="server"> <table cellpadding="4" cellspacing="0" border="0"> <tr><td colspan="2" height="5"></td></tr> <tr> <td valign="top">Photo:</td> <td><% if ( new FileInfo(Application["PHYSICALPATH"] + "test/mytestImage.jpg").Exists ) { %> <div style="float:left; background-color:#666666; padding:1px;"><img src="../test/mytestImage.jpg" width="190"></div> <div style="padding-top:8px; clear:both;"></div><br /> <% } if ( new FileInfo(Application["PHYSICALPATH"] + "test/mytestImage.gif").Exists ) { %> <div style="float:left; background-color:#666666; padding:1px;"><img src="../test/mytestImage.gif" width="190"></div> <div style="padding-top:8px; clear:both;"></div><br /> <% } if ( new FileInfo(Application["PHYSICALPATH"] + "test/mytestImage.png").Exists ) { %> <div style="float:left; background-color:#666666; padding:1px;"><img src="../test/mytestImage.png" width="190"></div> <div style="padding-top:8px; clear:both;"></div><br /> <% } %> <input id="PhotoUpload" runat="server" type="File" class="formcopy" /> <asp:customvalidator enableclientscript="false" cssclass="formcopy" display="dynamic" runat="server" text="* must be a .jpg, .jpeg, or .gif" controlToValidate="PhotoUpload" onservervalidate="ValidatePicture" /> </td> </tr> </table> <br /> <table cellpadding="4" cellspacing="0" border="0"> <tr> <td><asp:button ID="AddSaveButton" text="Upload" onclick="UploadBut_Click" cssclass="formcopy" runat="server" /></td> <td></td> </tr> </table> </form> </body> </html></code>
|
| Sign In·View Thread·PermaLink | 2.50/5 (5 votes) |
|
|
|
 |
|
|
Update to the main method for maintianing quality of the image:
Bitmap smallerImg = new Bitmap(new_width, new_height); Graphics g = Graphics.FromImage(smallerImg); g.SmoothingMode = SmoothingMode.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.PixelOffsetMode = PixelOffsetMode.HighQuality; foreach (PropertyItem pItem in UploadedImage.PropertyItems) { smallerImg.SetPropertyItem(pItem); } g.DrawImage(UploadedImage, 0, 0, new_width, new_height); UploadedImage.Dispose(); if ( !Extension.Equals(".png") ) { EncoderParameters myParams = new EncoderParameters(1); myParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Quality ); smallerImg.Save( FilePath + ImageName + Extension, GetEncoderInfo(MimeType), myParams); } else { smallerImg.Save( FilePath + ImageName + Extension , ImageFormat.Png); } smallerImg.Dispose();
|
| Sign In·View Thread·PermaLink | 3.33/5 (3 votes) |
|
|
|
 |
|
|
 |
|
|
Unless I'm missing sometime; this will lose the transparency layer of a png or gif format; is there a fix for this?
Lessons learned from 911:
1. United We Stand.
2. United’s We Fall.
Gulf War Syndrome survivors never have a good day. http://www.vetshelpcenter.com/
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Hi dude,
I just modified ur code for my project..it is very helpful for me now...Thanks a lot....
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click Try If FileUpload1.HasFile Then strFile = System.IO.Path.GetFileName(FileUpload1.FileName) filename = System.IO.Path.GetFileNameWithoutExtension(FileUpload1.FileName) strpath = "F:\testpic\" thbpath = "thumbs" & "\" & filename + ".png" FileUpload1.SaveAs(strpath & strFile) ImageResize() End If Catch ex As Exception lbl_msg.Text = ex.Message End Try End Sub Public Function ImageResize() As System.Web.UI.WebControls.Image Dim bm As New Bitmap(strpath & strFile) Dim bmn As New Bitmap(Image.FromHbitmap(bm.GetHbitmap), width, CInt(Math.Round(width * (bm.Height / bm.Width), 0))) Dim img As System.Drawing.Image = Image.FromHbitmap(bmn.GetHbitmap) Dim g As Graphics g = Graphics.FromImage(bmn) g.SmoothingMode = Drawing2D.SmoothingMode.HighQuality g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic g.PixelOffsetMode = Drawing2D.PixelOffsetMode.HighQuality g.DrawImage(bmn, 0, 0, 100, 100) Try img.Save(strpath & "\" & thbpath) Dim img_new As New System.Web.UI.WebControls.Image() Return img_new Catch ex As Exception lbl_msg.Text = ex.Message Return Nothing End Try End Function
I am a .Net profesional working...in a company...in India..
|
| Sign In·View Thread·PermaLink | 3.13/5 (4 votes) |
|
|
|
 |
|
|
hi, Hi thanks i also had the same problem. I would now like to save the resized image to a database then delete the temporary uploaded file.
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Hello,
you'll get this error:
The call is ambiguous between the following methods or properties: 'System.Math.Ceiling(decimal)' and 'System.Math.Ceiling(double)'
On line:
Int32 new_height = (Int32) Math.Ceiling( (old_height * new_width)/old_width );
to supress the error do this:
Int32 new_height = (Int32)Math.Ceiling(((double)old_height * (double)new_width) / (double)old_width);
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
 |
|
|
Sir, I am doing displaying and downloading of audio files in asp.net. I am displaying records using datagrid and bounded the data with data set. I've placed those audio file names in data base and files are in virtual directory. Now my problem is how to download a specific file? So please kindly give me the solution Thanking you, Sravani
|
| Sign In·View Thread·PermaLink | 1.50/5 (2 votes) |
|
|
|
 |
| | |