1.添加一个html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form action="Getmin.ashx" method="post" enctype="multipart/form-data">
图片:<input type="file" name="file" id="file" onchange="javascript:fileInfo();" />
<p style="font-size:12px;">原图宽:<label id="ow">0</label> 原图高:<label id="oh">0</label>
原图大小:<label id="os">0</label>KB</p>
<p>设置宽度:<input type="text" name="width" style="width:50px;"/>
<span style="color:#09a02c;font-size:12px">高度按原图比例折算</span></p>
<p><input type="submit" style="color:#ff6a00" value="下载缩略图" /> </p>
</form>
</body>
</html>
<script type="text/javascript">
//上传前获取图片信息(用html5的File)
function fileInfo() {
var f = document.getElementById("file").files[0];
var reader = new FileReader();
reader.readAsDataURL(f);
reader.onload = function (e) {
var data = e.target.result;
//加载一个图片获取宽度高度
var image = new Image();
image.src = data;
image.onload = function () {
var width = image.width;
var height = image.height;
var size = parseInt(f.size / 1024);
document.getElementById("ow").innerHTML = width;
document.getElementById("oh").innerHTML = height;
document.getElementById("os").innerHTML = size;
};
}
}
</script>
2.添加一个处理程序:ashx
public void ProcessRequest(HttpContext context)
{
//1.获取用户上传的文件流
HttpPostedFile file = context.Request.Files[0];
//获取文件名
string fileName = file.FileName;
//获取扩展名
string Extension = Path.GetExtension(fileName).ToUpper();
//2.根据用户上传的文件流创建一个图片
using (Image originalImage = Image.FromStream(file.InputStream))
{
//获取原始图片的宽和高
int owidth = originalImage.Width;
int oheight = originalImage.Height;
//缩略图的宽
int mwidth = Convert.ToInt32(context.Request.Form["width"]);
//等比例的高,取整数
int mheight = mwidth * oheight / owidth;
//3.根据原始图片,等比例创建一个缩小后的图片
using (Image minImage = new Bitmap(mwidth, mheight))
{
//4.把大图片内容画到小图片上
//基于小图创建一个画布对象
Graphics gmin = Graphics.FromImage(minImage);
//把大图画到小图上
gmin.DrawImage(originalImage, 0, 0, mwidth, mheight);
//5.下载缩略图
MemoryStream ms = new MemoryStream();
//判断图片类型
ImageFormat imageFormat = null;
string ContentType = "";
switch (Extension)
{
case ".JPG": imageFormat = ImageFormat.Jpeg; ContentType = "image/jpeg"; break;
case ".PNG": imageFormat = ImageFormat.Png; ContentType = "image/png"; break;
case ".GIF": imageFormat = ImageFormat.Gif; ContentType = "image/gif"; break;
//................如需要其他图片格式继续添加
}
minImage.Save(ms,imageFormat);
context.Response.ClearContent();
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
context.Response.ContentType=ContentType;
context.Response.BinaryWrite(ms.ToArray());
context.Response.End();
}
}
}
public bool IsReusable
{
get
{
return false;
}
}