当前位置:Gxlcms > asp.net > asp.net生成缩略图实现代码

asp.net生成缩略图实现代码

时间:2021-07-01 10:21:17 帮助过:45人阅读

代码如下:
  1. <br>using System; <br>using System.Collections.Generic; <br>using System.Linq; <br>using System.Web; <br>using System.Drawing; <br>using System.IO; <br>namespace web三层 <br>{ <br>/// <summary> <br>/// 显示请求图片的缩略图,以宽度100像素为最大单位 <br>/// </summary> <br>public class imgSmall : IHttpHandler <br>{ <br>//图片所在文件夹 <br>static string picturesPath = @"d:\wordpictures\"; <br>public void ProcessRequest(HttpContext context) <br>{ <br>context.Response.ContentType = "image/jpeg"; <br>//获取到传递过来的img字符串,比如 <br>//http://localhost:5002/imgSmall.ashx?img=abacus8.jpg这种 <br>string img = context.Request.Params["img"]; <br>string path = picturesPath + img; <br>//如果文件存在才会去读取,减少使用try,catch,提高程序性能 <br>if (File.Exists(path)) <br>{ <br>//载入这个图片 <br>Image big = Image.FromFile(path); <br>//如果可以获取到文件,才会执行下面的代码 <br>if (big != null) <br>{ <br>//设定最大的宽度,可以修改来生成更小的缩略图 <br>int newWidth = 100; <br>//根据图片的宽高比来生成一个位图 <br>Bitmap bitmap = new Bitmap(newWidth, newWidth * big.Height / big.Width); <br>//根据图板来创建一个图画 <br>Graphics g = Graphics.FromImage(bitmap); <br>using (g) <br>{ <br>//将大图big画到自己定义的小图中bitmap <br>g.DrawImage(big, 0, 0, bitmap.Width, bitmap.Height); <br>//直接将处理好的位图保存到响应
输出流中,格式为jpeg!
bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
else
{
//否则就发送一个文件不存在的信息到浏览器
context.Response.ContentType = "text/html";
context.Response.Write("文件不存在");
//或者发送一个文件不存在的图片
//context.Response.WriteFile("todo此处修改为图片所在路径");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}

这是一个一般处理程序,只需要给其发送一个文件名称的参数就可以在浏览器上显示出图片(可以修改成发送一个图片的序号id),比如下面的GridView控件中使用了此处理程序image

 

缩略图字段中将其DataImageUrlField设置为文件名,这个字段是数据库中一个字段(初学的时候我喜欢用中文字段,比较好理解),再将其DataImageUrlFormatString设置为:imgSmall.ashx?img={0},这样在生成html代码的时候就会把{0}替换成文件名这个字段的内容,实际的效果如下图:

image

缩略图非常的小,才3040字节,看官也可以发现当浏览器请求图片时,请求的地址是imgSmall.ashx?img=abacus8.jpg

人气教程排行