In this article you will learn about how to resize an Image at run-time using C# asp.Net.Resize an image with good quality, and having less weight of an image so that webpages will load it faster.
should reference the following namespases.
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
#region Events
protected void ResizeButton_click(object sender,EventArgs e)
{
string path = Server.MapPath("~/Images");
ResizePhoto(path);
}
#endregion
public static void ResizePhoto(string imgpath)
{
//if you want dynamically to change images set path insead of 3904.jpg
using (var image = System.Drawing.Image.FromFile(string.Concat(imgpath, "/3904.jpg")))
using (var newImage = ScaleImage(image, 350, 450))
{
// dynamically change the name of new size image by any customized name (e.g:datetime )
newImage.Save(string.Concat(imgpath, "/test.jpg"), ImageFormat.Png);
}
}
public static System.Drawing.Image ScaleImage(System.Drawing.Image image, int maxWidth, int maxHeight)
{
var ratioX = (double)maxWidth / image.Width;
var ratioY = (double)maxHeight / image.Height;
var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(newWidth, newHeight);
using (var graphics = Graphics.FromImage(newImage))
graphics.DrawImage(image, 0, 0, newWidth, newHeight);
return newImage;
}
Post your comments / questions
Recent Article
- How to create custom 404 error page in Django?
- Requested setting INSTALLED_APPS, but settings are not configured. You must either define..
- ValueError:All arrays must be of the same length - Python
- Check hostname requires server hostname - SOLVED
- How to restrict access to the page Access only for logged user in Django
- Migration admin.0001_initial is applied before its dependency admin.0001_initial on database default
- Add or change a related_name argument to the definition for 'auth.User.groups' or 'DriverUser.groups'. -Django ERROR
- Addition of two numbers in django python
Related Article