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

复制代码 代码如下:

  using System;

  using System.Collections.Generic;

  using System.Linq;

  using System.Web;

  using System.Drawing;

  using System.IO;

  namespace web三层

  {

  /// <summary>

  /// 显示请求图片的缩略图,以宽度100像素为最大单位

  /// </summary>

  public class imgSmall : IHttpHandler

  {

  //图片所在文件夹

  static string picturesPath = @"d:\wordpictures\";

  public void ProcessRequest(HttpContext context)

  {

  context.Response.ContentType = "image/jpeg";

  //获取到传递过来的img字符串,比如

  //http://localhost:5002/imgSmall.ashx?img=abacus8.jpg这种

  string img = context.Request.Params["img"];

  string path = picturesPath + img;

  //如果文件存在才会去读取,减少使用try,catch,提高程序性能

  if (File.Exists(path))

  {

  //载入这个图片

  Image big = Image.FromFile(path);

  //如果可以获取到文件,才会执行下面的代码

  if (big != null)

  {

  //设定最大的宽度,可以修改来生成更小的缩略图

  int newWidth = 100;

  //根据图片的宽高比来生成一个位图

  Bitmap bitmap = new Bitmap(newWidth, newWidth * big.Height / big.Width);

  //根据图板来创建一个图画

  Graphics g = Graphics.FromImage(bitmap);

  using (g)

  {

  //将大图big画到自己定义的小图中bitmap

  g.DrawImage(big, 0, 0, bitmap.Width, bitmap.Height);

  //直接将处理好的位图保存到响应输出流中,格式为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控件中使用了此处理程序

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

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

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

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