Compress Image in asp.net


Description:-
Hi, in this article we will see about how to compress Image file size and save in folder. here i have an used input control of type File. here people will select an image add there is some code to store it in a folder within the project. For simply storing there is no problem. But the thing is i want to compress the Images size before saving it in the folder. I want an image to compress in size of the space that it take.
Default.aspx:-
<div>
   <asp:FileUpload ID="fileupload1" runat="server" />
   <asp:Button ID="btnsave" runat="server" Text="Save" OnClick="btnsave_Click" />
</div>

Default.aspx.cs:-


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 = System.Drawing.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);
   }
}

Related Posts

Previous
Next Post »

1 comments:

comments

Thanks for comments.....