62,046
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// 缩放图片不带水印
/// </summary>
/// <param name="hifile"></param>
/// <param name="imgName"></param>
/// <param name="aWidth"></param>
/// <param name="aHeight"></param>
/// <returns></returns>
public string UpImages(FileUpload hifile, string imgName, Unit aWidth, Unit aHeight)
{
string strOldFilePath = hifile.PostedFile.FileName;
//取得上传文件的扩展名
string strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));
//生成原图
Byte[] oFileByte = new byte[hifile.PostedFile.ContentLength];
System.IO.Stream oStream = hifile.PostedFile.InputStream;
System.Drawing.Image oImage = System.Drawing.Image.FromStream(oStream);
int oWidth = oImage.Width; //原图宽度
int oHeight = oImage.Height; //原图高度
int tWidth = Convert.ToInt32(aWidth.Value); //设置缩略图初始宽度
int tHeight = Convert.ToInt32(aHeight.Value); //设置缩略图初始高度
if (imgName == "")
{
//图片名
imgName = DateTime.Now.ToString("yyyyMMddHHmmss") + DateTime.Now.Millisecond.ToString() + strExtension;
//图片存储相对路径
}
string path = WebPath.PhysicalApplicationPath + "/UpImage/" + imgName;
if (oWidth <= tWidth && oHeight <= tHeight)
{
try
{
hifile.PostedFile.SaveAs(path);
}
catch
{
imgName = "no";
}
}
else
{
//按比例计算出缩略图的宽度和高度
if (oWidth >= oHeight)
{
tHeight = (int)Math.Floor(Convert.ToDouble(oHeight) * (Convert.ToDouble(tWidth) / Convert.ToDouble(oWidth)));
}
else
{
tWidth = (int)Math.Floor(Convert.ToDouble(oWidth) * (Convert.ToDouble(tHeight) / Convert.ToDouble(oHeight)));
}
//生成缩略原图
Bitmap tImage = new Bitmap(tWidth, tHeight);
Graphics g = Graphics.FromImage(tImage);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量插值法
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;//设置高质量,低速度呈现平滑程度
g.Clear(Color.Transparent); //清空画布并以透明背景色填充
g.DrawImage(oImage, new Rectangle(0, 0, tWidth, tHeight), new Rectangle(0, 0, oWidth, oHeight), GraphicsUnit.Pixel);
//存储图片所需的绝对路径
try
{
//以JPG格式保存图片
tImage.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch
{
imgName = "no";
}
finally
{
//释放资源
oImage.Dispose();
g.Dispose();
tImage.Dispose();
}
}
return imgName;
}