通过一般处理程序生成缩略图

创建一个一般处理程序smallImg.ashx
要显示图片的时候直接把img标签的src指向smallImg.ashx就行了,后面可以加上要传的参数。

smallImg.ashx代码如下:

 1 <%@ WebHandler Language="C#" Class="SmallImg" %>
2
3 using System;
4 using System.Web;
5 using System.Drawing;
6 public class ImgSmall : IHttpHandler {
7
8 //生成图片缩略图
9 public void ProcessRequest (HttpContext context) {
10 context.Response.ContentType = "image/jpeg";
11 //url传来的图片名称
12 string img = context.Request.QueryString["img"];
13
14 if (!string.IsNullOrEmpty(img))
15 {
16 //获取图片的物理路径
17 string path = context.Request.MapPath("images/" + img);
18 //加载大图
19 Image big = Image.FromFile(path);
20
21 float oldWidth = big.Width;
22 float oldHeight = big.Height;
23 float newWidth = 150;
24 float newHeight = 100;
25 //保持横纵比例
26 if (oldWidth / oldHeight > newWidth / newHeight) //宽了,就要以宽为准
27 {
28 newHeight = newWidth * oldHeight / oldWidth;
29 }
30 else
31 {
32 newWidth = newHeight * oldWidth / oldHeight;//高了,就要以高为准
33 }
34
35
36 //生成小图
37 Bitmap bitmap = new Bitmap((int)newWidth,(int)newHeight);
38
39 Graphics g = Graphics.FromImage(bitmap);
40 //把大图 画到小图上
41 g.DrawImage(big, 0, 0, bitmap.Width, bitmap.Height);
42 //释放资源
43 g.Dispose();
44
45 //把bitmap输出到浏览器
46 bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
47 }
48
49 }
50
51 public bool IsReusable {
52 get {
53 return false;
54 }
55 }
56
57 }

最后可以对图片地址进行url重写,让页面代码美观一点,这个可有可无。

posted @ 2012-01-30 21:05  JesseLZJ  阅读(447)  评论(0编辑  收藏  举报