asp. net image compression method after the specified size
- 2020-06-07 04:23:16
- OfStack
/// <summary>
/// The compressed image
/// </summary>
/// <returns></returns>
public string ResizePic()
{
#region Compressed image start
bool IsImgFile = true; // Determine if it is an image file
string filePathName = "123"; // Path to file storage (folder name)
string fileName = "a.jpg"; // The original name of the uploaded file
string fileSysName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + fileName; // Modified file name
string filePath = ""; // The file path
string strImgPath = "/fileupload/"; // Upload path
if (IsImgFile)
{
int maxWidth = 600; // Maximum image width limit
int maxHeight = 400; // Maximum image height limit
System.Drawing.Image imgPhoto =
System.Drawing.Image.FromFile(Server.MapPath(strImgPath) + filePathName + "/" + fileSysName);
int imgWidth = imgPhoto.Width;
int imgHeight = imgPhoto.Height;
if (imgWidth > imgHeight) // If the width exceeds the height, compress by width
{
if (imgWidth > maxWidth) // If the image width exceeds the limit
{
float toImgWidth = maxWidth; // Image width after compression
float toImgHeight = imgHeight / (float)(imgWidth / toImgWidth); // Image height after compression
System.Drawing.Bitmap img = new System.Drawing.Bitmap(imgPhoto,
int.Parse(toImgWidth.ToString()),
int.Parse(toImgHeight.ToString()));
string strResizePicName = Server.MapPath(strImgPath) + filePathName + "/_small_" + fileSysName;
img.Save(strResizePicName); // Save the compressed image
filePath = strImgPath + filePathName + "/_small_" + fileSysName; // Returns the compressed image path
}
}
else
{
if (imgHeight > maxHeight)
{
float toImgHeight1 = maxHeight;
float toImgWidth1 = imgWidth / (float)(imgHeight / toImgHeight1);
System.Drawing.Bitmap img = new System.Drawing.Bitmap(imgPhoto,
int.Parse(toImgWidth1.ToString()),
int.Parse(toImgHeight1.ToString()));
string strResizePicName = Server.MapPath(strImgPath) + filePathName + "/_small_" + fileSysName;
img.Save(strResizePicName);
filePath = strImgPath + filePathName + "/_small_" + fileSysName;
}
}
}
return filePath;
#endregion
}