我有如下所示的将图像保存为jpeg的方法.
我想以相同的高度和宽度保存所有图片,而不会失真.
我怎样才能做到这一点?
请帮忙
public void SaveFileOnDisk(MemoryStream ms, string FileName)
{
try
{
string appPath = HttpContext.Current.Request.ApplicationPath;
string physicalPath = HttpContext.Current.Request.MapPath(appPath);
string strpath = physicalPath + "\\Images";
string WorkingDirectory = strpath;
System.Drawing.Image imgSave = System.Drawing.Image.FromStream(ms);
Bitmap bmSave = new Bitmap(imgSave);
Bitmap bmTemp = new Bitmap(bmSave);
Graphics grSave = Graphics.FromImage(bmTemp);
grSave.DrawImage(imgSave, 0, 0, imgSave.Width, imgSave.Height);
bmTemp.Save(WorkingDirectory + "\\" + FileName + ".jpg");
imgSave.Dispose();
bmSave.Dispose();
bmTemp.Dispose();
grSave.Dispose();
}
catch (Exception ex)
{
//lblMsg.Text = "Please try again later.";
}
}
解决方法:
调整图像大小并保存
Private void ResizeImage(Image img, double maxWidth, double maxHeight)
{
double srcWidth = img.Source.Width;
double srcHeight = img.Source.Height;
double resizeWidth = srcWidth;
double resizeHeight = srcHeight;
double aspect = resizeWidth / resizeHeight;
if (resizeWidth > maxWidth)
{
resizeWidth = maxWidth;
resizeHeight = resizeWidth / aspect;
}
if (resizeHeight > maxHeight)
{
aspect = resizeWidth / resizeHeight;
resizeHeight = maxHeight;
resizeWidth = resizeHeight * aspect;
}
img.Width = resizeWidth;
img.Height = resizeHeight;
}
您可以使用此代码将图像调整为所需的尺寸,然后再保存