Simply resize an uploaded image
I got an E-Mail from a student this morning asking how to thumbnail an uploaded image. Here is a “quick” solution (there are a few things you can do to increase quality, set JPEG compression factor or keep gif transparency). If you like to dig deeper have a look at one of the articles I wrote for the DotNetPro magazine’s #Talk column.
<%@ Page Language="C#" %>
<script runat="server" Language="C#">
public void UploadFile(object sender, EventArgs e) {
System.Drawing.Image _img =
System.Drawing.Image.FromStream(
this.InputTypeFile.PostedFile.InputStream);
int _maxWidth = 100;
int _maxHeight = 100;
int _width = _img.Width;
int _height = _img.Height;
string _filename =
System.IO.Path.GetFileName(
this.InputTypeFile.PostedFile.FileName);
string _uploadPath =
System.IO.Path.Combine(
Server.MapPath(".\upload\"),
_filename);
if (_width > _height){
width = Math.Abs((int)(height * _img.Width / _img.Height));
_height = _maxHeight;
} else {
_height = Math.Abs((int)(_maxWidth * _img.Height / _img.Width));
_width = _maxWidth;
}
System.Drawing.Image _newImg =
_img.GetThumbnailImage(width, height, null, null);
_newImg.Save(_uploadPath);
_img.Dispose();
}
</script>
<html>
<body>
<form id="form1" runat="server">
<input id="InputTypeFile" type="file" runat="server" />
<asp:Button ID="Submit" OnClick="UploadFile" Text="Upload" />
</form>
</body>
</html>