日期:2008-09-20  浏览次数:20394 次

以前,在页面上实现缩略图必须借助第三方组件。现在,有了.NET,就可以很轻松地实现缩略图。下面就是实现缩略图的例子。

关键字:C# ,ASP.NET,缩略图

实例下载:http://www.lionsky.net/MyWebSite/DownSoft/list.aspx?id=221

ToThumbnailImage.aspx


<%@ Page language="c#" Codebehind="ToThumbnailImage.aspx.cs" Src="ToThumbnailImage.aspx.cs" AutoEventWireup="false" Inherits="Exam_C.ToThumbnailImage" %>
<html>
<head>
<title>Lion互动网络 =>生成缩略图</title>
</head>
<body>
<form id="Form1" method="post" runat="server">
</form>
</body>
</html>



ToThumbnailImage.aspx.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Drawing.Imaging;
namespace Exam_C
{
/// <summary>
/// ToThumbnailImage 的摘要说明。
/// </summary>
public class ToThumbnailImage : System.Web.UI.Page
{
/*
Create By lion
2003-05-20 19:00
Copyright (C) 2004 www.LionSky.Net. All rights reserved.
Web: http://www.Lionsky.net ;
Email: lion-a@sohu.com
*/


static Hashtable htmimes=new Hashtable();
internal readonly string AllowExt = ".jpe|.jpeg|.jpg|.png|.tif|.tiff|.bmp";

#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
#region htmimes[".jpe"]="image/jpeg";
htmimes[".jpeg"]="image/jpeg";
htmimes[".jpg"]="image/jpeg";
htmimes[".png"]="image/png";
htmimes[".tif"]="image/tiff";
htmimes[".tiff"]="image/tiff";
htmimes[".bmp"]="image/bmp";
#endregion
//调用生成缩略图方法
ToThumbnailImages("lionsky.jpg","b.gif",300);
}
#endregion

#region Helper

/// <summary>
/// 获取图像编码解码器的所有相关信息
/// </summary>
/// <param name="mimeType">包含编码解码器的多用途网际邮件扩充协议 (MIME) 类型的字符串</param>
/// <returns>返回图像编码解码器的所有相关信息</returns>
static ImageCodecInfo GetCodecInfo(string mimeType)
{
ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
foreach(ImageCodecInfo ici in CodecInfo)
{
if(ici.MimeType == mimeType)return ici;
}
return null;
}

/// <summary>
/// 检测扩展名的有效性
/// </summary>
/// <param name="sExt">文件名扩展名</param>
/// <returns>如果扩展名有效,返回true,否则返回false.</returns>
bool CheckValidExt(string sExt)
{
bool flag=false;
string[] aExt = AllowExt.Split('|');
foreach(string filetype in aExt)
{
if(filetype.ToLower()==sExt)
{
flag = true;
break;
}
}
return flag;
}

/// <summary>
/// 保存图片
/// </summary>
/// <param name="image">Image 对象</param>
/// <param name="savePath">保存路径</param>
/// <param name="ici">指定格式的编解码参数</param>
void SaveImage(System.Drawing.Image image,string savePath,ImageCodecInfo ici)
{
//设置 原图片 对象的 EncoderParameters 对象
EncoderParameters parameters = new EncoderParameters(1);
parameters.Param[0] = new EncoderParameter(Encoder.Quality, ((long) 90));
image.Save(savePath, ici, parameters);
parameters.Dispose();
}
#endregion

#region Methods

/