Bạn thiết kế một website cho khách hàng, giao quyền admin cho khách hàng có thể cập nhật dữ liệu. Nhưng khi khách hàng upload hình ảnh sản phẩm lên website, làm thế nào có thể xử lý được khi khách hàng upload ảnh quá lớn khiến cho tốc độ load website bị chậm và gây hao tốn dung lượng hosting. WEBXAULA sẽ giới thiệu với bạn cách thay đổi kích thước ảnh ngay khi admin upload ảnh lên host bằng ASP.NET
public void ThayDoiKichThuocAnh(string ImageSavePath, string fileName,
int MaxWidthSideSize, Stream Buffer)
{
int intNewWidth;
int intNewHeight;
System.Drawing.Image imgInput = System.Drawing.Image.FromStream(Buffer);
ImageCodecInfo myImageCodecInfo;
myImageCodecInfo = GetEncoderInfo("image/jpeg");
//
System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
EncoderParameters myEncoderParameters = new EncoderParameters(1);
EncoderParameter myEncoderParameter;
//Giá trị width và height nguyên thủy của ảnh;
int intOldWidth = imgInput.Width;
int intOldHeight = imgInput.Height;
//Kiểm tra xem ảnh ngang hay dọc;
int intMaxSide;
/*if (intOldWidth >= intOldHeight)
{
intMaxSide = intOldWidth;
}
else
{
intMaxSide = intOldHeight;
}*/
//Để xác định xử lý ảnh theo width hay height thì bạn bỏ note phần trên;
//Ở đây mình chỉ sử dụng theo width nên gán luôn intMaxSide= intOldWidth; ^^;
intMaxSide = intOldWidth;
if (intMaxSide > MaxWidthSideSize)
{
//Gán width và height mới.
double dblCoef = MaxWidthSideSize / (double)intMaxSide;
intNewWidth = Convert.ToInt32(dblCoef * intOldWidth);
intNewHeight = Convert.ToInt32(dblCoef * intOldHeight);
}
else
{
//Nếu kích thước width/height (intMaxSide) cũ ảnh nhỏ hơn MaxWidthSideSize thì giữ nguyên //kích thước cũ;
intNewWidth = intOldWidth;
intNewHeight = intOldHeight;
}
//Tạo một ảnh bitmap mới;
Bitmap bmpResized = new Bitmap(imgInput, intNewWidth, intNewHeight);
//Phần EncoderParameter cho phép bạn chỉnh chất lượng hình ảnh ở đây mình để chất lượng tốt //nhất là 100L;
myEncoderParameter = new EncoderParameter(myEncoder, 100L);
myEncoderParameters.Param[0] = myEncoderParameter;
//Lưu ảnh;
bmpResized.Save(ImageSavePath + fileName, myImageCodecInfo, myEncoderParameters);
//Giải phóng tài nguyên;
//Buffer.Close();
imgInput.Dispose();
bmpResized.Dispose();
}
private ImageCodecInfo GetEncoderInfo(String mimeType)
{
int j;
ImageCodecInfo[] encoders;
encoders = ImageCodecInfo.GetImageEncoders();
for (j = 0; j < encoders.Length; ++j)
{
if (encoders[j].MimeType == mimeType)
return encoders[j];
}
return null;
}
Đến khi cần sử dụng hàm thì bạn gọi như sau là sẽ đồng thời thay đổi kích thước ảnh theo quy định của mình và upload ảnh đã resize lên host.