Thursday, October 3, 2013

How to reduce images size by c# code?

 
protected void btnsave_Click(object sender, EventArgs e)



{
 
string filename = Path.GetFileName(fileupload1.PostedFile.FileName);

string targetPath = Server.MapPath("Images1/" + filename);

Stream strm = fileupload1.PostedFile.InputStream;

var targetFile = targetPath;



GenerateThumbnails(1, strm, targetFile);



}
 
 
 
 





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);

thumbnailImg.Save(targetPath, System.Drawing.Imaging.ImageFormat.Jpeg);



}

}


No comments:

Post a Comment