最新文章专题视频专题问答1问答10问答100问答1000问答2000关键字专题1关键字专题50关键字专题500关键字专题1500TAG最新视频文章推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37视频文章20视频文章30视频文章40视频文章50视频文章60 视频文章70视频文章80视频文章90视频文章100视频文章120视频文章140 视频2关键字专题关键字专题tag2tag3文章专题文章专题2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章专题3
当前位置: 首页 - 科技 - 知识百科 - 正文

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

来源:动视网 责编:小采 时间:2020-11-27 22:42:33
文档

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

asp.net生成缩略图实现代码: 代码如下:using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Drawing; using System.IO; namespace web三层 { /// <summary> /// 显示请求图片
推荐度:
导读asp.net生成缩略图实现代码: 代码如下:using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Drawing; using System.IO; namespace web三层 { /// <summary> /// 显示请求图片


代码如下:

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控件中使用了此处理程序image

 

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

image

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

文档

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

asp.net生成缩略图实现代码: 代码如下:using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Drawing; using System.IO; namespace web三层 { /// <summary> /// 显示请求图片
推荐度:
标签: 生成 实现 代码
  • 热门焦点

最新推荐

猜你喜欢

热门推荐

专题
Top