部分代码已经加入注释,仔细阅读代码应该不难理解。下面介绍ashx中AJAX调用方法,我们在AJAX异步上传图片成功后对源图片进行"PS"。关键代码片段如下:
//上传成功后网站内源图片相对路径
string relativePath = System.Web.HttpContext.Current.Request.ApplicationPath
+ string.Format(@"Content/Upload/Images/{0}", fileName);
/*
比例处理
微缩图高度(DefaultHeight属性值为 400)
*/
System.Drawing.Image img = System.Drawing.Image.FromFile(toFile);
int width = img.Width;
int height = img.Height;
float ratio = (float)width / height;
//微缩图高度和宽度
int newHeight = height <= DefaultHeight ? height : DefaultHeight;
int newWidth = height <= DefaultHeight ? width : Convert.ToInt32(DefaultHeight * ratio);
FileInfo generatedfile = new FileInfo(toFile);
string newFileName = "Thumb_" + generatedfile.Name;
string newFilePath = Path.Combine(generatedfile.DirectoryName, newFileName);
PictureHandler.CreateThumbnailPicture(toFile, newFilePath, newWidth, newHeight);
string thumbRelativePath = System.Web.HttpContext.Current.Request.ApplicationPath
+ string.Format(@"/Content/Upload/Images/{0}", newFileName);
//返回原图和微缩图的网站相对路径
relativePath = string.Format("{0},{1}", relativePath, thumbRelativePath);
return relativePath;
string relativePath = System.Web.HttpContext.Current.Request.ApplicationPath
+ string.Format(@"Content/Upload/Images/{0}", fileName);
/*
比例处理
微缩图高度(DefaultHeight属性值为 400)
*/
System.Drawing.Image img = System.Drawing.Image.FromFile(toFile);
int width = img.Width;
int height = img.Height;
float ratio = (float)width / height;
//微缩图高度和宽度
int newHeight = height <= DefaultHeight ? height : DefaultHeight;
int newWidth = height <= DefaultHeight ? width : Convert.ToInt32(DefaultHeight * ratio);
FileInfo generatedfile = new FileInfo(toFile);
string newFileName = "Thumb_" + generatedfile.Name;
string newFilePath = Path.Combine(generatedfile.DirectoryName, newFileName);
PictureHandler.CreateThumbnailPicture(toFile, newFilePath, newWidth, newHeight);
string thumbRelativePath = System.Web.HttpContext.Current.Request.ApplicationPath
+ string.Format(@"/Content/Upload/Images/{0}", newFileName);
//返回原图和微缩图的网站相对路径
relativePath = string.Format("{0},{1}", relativePath, thumbRelativePath);
return relativePath;
三、程序运行截图:
上传前:
上传后:
四、 小结:
我使用该方法主要是为了解决打印报表时由于图片大小没有合理的比例规范导致报表样式变形,同样该方法也适合网站或论坛由用户上传源图片生成微缩头像等。
如果您感兴趣可以在这里下载本例DEMO。
最后希望本文能够帮助您解决开发中的类似问题。