1 /// <summary>
2 /// 压缩图片
3 /// </summary>
4 /// <returns></returns>
5 public string ResizePic()
6 {
7 #region 压缩图片开始
8 bool IsImgFile = true; //判断是否为图片文件
9 string filePathName = "123"; //文件存储的路径(文件夹名称)
10 string fileName = "a.jpg"; //上传文件的原始名称
11 string fileSysName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + fileName; //修改后的文件名称
12 string filePath = ""; //文件路径
13 string strImgPath = "/fileupload/"; //上传路径
14 if (IsImgFile)
15 {
16 int maxWidth = 600; //图片宽度最大限制
17 int maxHeight = 400; //图片高度最大限制
18 System.Drawing.Image imgPhoto =
19 System.Drawing.Image.FromFile(Server.MapPath(strImgPath) + filePathName + "/" + fileSysName);
20 int imgWidth = imgPhoto.Width;
21 int imgHeight = imgPhoto.Height;
22 if (imgWidth > imgHeight) //如果宽度超过高度以宽度为准来压缩
23 {
24 if (imgWidth > maxWidth) //如果图片宽度超过限制
25 {
26 float toImgWidth = maxWidth; //图片压缩后的宽度
27 float toImgHeight = imgHeight / (float)(imgWidth / toImgWidth); //图片压缩后的高度
28
29 System.Drawing.Bitmap img = new System.Drawing.Bitmap(imgPhoto,
30 int.Parse(toImgWidth.ToString()),
31 int.Parse(toImgHeight.ToString()));
32 string strResizePicName = Server.MapPath(strImgPath) + filePathName + "/_small_" + fileSysName;
33 img.Save(strResizePicName); //保存压缩后的图片
34 filePath = strImgPath + filePathName + "/_small_" + fileSysName; //返回压缩后的图片路径
35 }
36 }
37 else
38 {
39 if (imgHeight > maxHeight)
40 {
41 float toImgHeight1 = maxHeight;
42 float toImgWidth1 = imgWidth / (float)(imgHeight / toImgHeight1);
43
44 System.Drawing.Bitmap img = new System.Drawing.Bitmap(imgPhoto,
45 int.Parse(toImgWidth1.ToString()),
46 int.Parse(toImgHeight1.ToString()));
47 string strResizePicName = Server.MapPath(strImgPath) + filePathName + "/_small_" + fileSysName;
48 img.Save(strResizePicName);
49 filePath = strImgPath + filePathName + "/_small_" + fileSysName;
50 }
51 }
52 }
53 return filePath;
54 #endregion
55 }