菜鸟分享,大小可随意调节缩略图代码。希望对有需要的朋友有帮助
在这个.net论坛上许久了,一直都是一个菜鸟。忽然的,想陆续的分享一些功能上的代码,供和我一样正在奋斗的朋友们学习。我是自学的,没有在软件公司干过,所以,呵呵,高手朋友们可以潇洒的飘过,若是您感兴趣,欢迎批评指正。
以下是一段上传图片,并同时生成一张大小可以随意调节且不失真的缩略图代码。
前台:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="NewsCss.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<div>
<div class="sc_chanpin">
<asp:Label ID="Label1" runat="server" Text="选择上传的图片:"></asp:Label>
<asp:FileUpload ID="FileUpload1" runat="server" />
</div>
<div class="sc_chanpin">
<asp:Label ID="Label2" runat="server" Text="写入图片介绍:"></asp:Label>
<asp:TextBox ID="shuoming" runat="server" TextMode="MultiLine"></asp:TextBox>
</div>
<asp:Label ID="lbMessage" runat="server" Text="Label"></asp:Label>
<asp:ImageButton ID="ImageButton1" runat="server" OnClick="imgBtnLoad_Click" />
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Model;
public partial class houtai_chanpinManager : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ }
protected void imgBtnLoad_Click(object sender, ImageClickEventArgs e)
{
if (!FileUpload1.HasFile)
{
lbMessage.Text = "请选择上传图片!";
return;
}
else
{
try
{
//获取上传文件路径
string filePath = FileUpload1.PostedFile.FileName;
//获取上传文件后缀
string fileExt = filePath.Substring(filePath.LastIndexOf(".") + 1);
//限定上传格式
if (fileExt.ToLower() == "gif" || fileExt.ToLower() == "jpg" || fileExt.ToLower() == "bmp" || fileExt.ToLower() == "png")
{
if (FileUpload1.PostedFile.ContentLength > 5120000)
{
lbMessage.Text = "限定上传图片的大小不能超出5M!";
return;
}
else
{
//取文件名
string nowTime = filePath.Substring(filePath.LastIndexOf("//") + 1);
string fileName = nowTime + "." + fileExt;
//源文件保存路径
string savePath = Server.MapPath("../image/");
//缩略图保存路径
string imgPath = Server.MapPath("../images/");
//上传图片
FileUpload1.PostedFile.SaveAs(savePath + fileName);
//创建自定义Album类对象实例
Album am = new Album();
//根据图片的宽、高比例生成缩略图
System.Drawing.Image img = System.Drawing.Image.FromFile(savePath + fileName);
if (img.Width >= img.Height)
{
am.GetThumbnail(savePath + fileName, imgPath + fileName, 280, 110, "Cut");
}
else
{
am.GetThumbnail(savePath + fileName, imgPath + fileName, 280, 110, "Cut");
}
//文件类型
string p_type = FileUpload1.PostedFile.ContentType;
//文件大小
int p_size = FileUpload1.PostedFile.ContentLength;
//调用类方法将数据插入到数据库
int result = am.AddPhoto(shuoming.Text.Trim(), fileName);
}
}
else
{
lbMessage.Text = "只允许上传gif,jpg,bmp,png格式的图片文件!";
return;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
}
}
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
//引入命名空间
using System.Data.SqlClient;
using System.IO;
namespace Model
{
/// <summary>
///数据连接
/// </summary>
public class Album
{
//私有变量,数据库连接
protected SqlConnection conn;
protected string ConnectionString;
public Album()//构造函数
{
ConnectionString = ConfigurationManager.AppSettings["connstr"];
}
/// <summary>
/// 添加图片信息
/// </summary>
/// <returns></returns>
public int AddPhoto(string shuoming, string url)
{
//创建Connection对象
string sql = "server=XXXXXX;Database=XXXXXX;User ID=XXXXXX;Password=XXXXXX";
SqlConnection conn = new SqlConnection(sql);
//定义SQL语句
string sqlstr = "insert into XX(shuoming,Url) "
+ "values(@shuoming,@url)";//定义两个变量将图片说明和图片名称插入数据库
//创建Command对象
SqlCommand cmd = new SqlCommand(sqlstr, conn);
//设置参数并赋值
cmd.Parameters.Add("@shuoming", SqlDbType.Text).Value = shuoming;
cmd.Parameters.Add("@url", SqlDbType.NVarChar).Value = url;
int result = -1;
try
{
//打开数据库连接
conn.Open();
//执行命令
result = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
//抛出异常
throw new Exception(ex.Message, ex);
}
finally
{
//关闭连接
conn.Close();
}
return result;
}
/// <summary>
/// 生成缩略图//
/// </summary>
public void GetThumbnail(string serverImagePath, string thumbnailImagePath, int width, int height, string p)
{
System.Drawing.Image serverImage = System.Drawing.Image.FromFile(serverImagePath);
//画板大小
int towidth = width;
int toheight = height;
//缩略图矩形框的像素点
int x = 0;
int y = 0;
int ow = serverImage.Width;
int oh = serverImage.Height;
switch (p)
{
case "WH"://指定高宽缩放(可能变形)
break;
case "W"://指定宽,高按比例
toheight = serverImage.Height * width / serverImage.Width;
break;
case "H"://指定高,宽按比例
towidth = serverImage.Width * height / serverImage.Height;
break;
case "Cut"://指定高宽裁减(不变形)
if ((double)serverImage.Width / (double)serverImage.Height > (double)towidth / (double)toheight)
{
oh = serverImage.Height;
ow = serverImage.Height * towidth / toheight;
y = 0;
x = (serverImage.Width - ow) / 2;
}
else
{
ow = serverImage.Width;
oh = serverImage.Width * height / towidth;
x = 0;
y = (serverImage.Height - oh) / 2;
}
break;
default:
break;
}
//新建一个bmp图片
System.Drawing.Image bm = new System.Drawing.Bitmap(towidth, toheight);
//新建一个画板
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bm);
//设置高质量插值法
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
//设置高质量,低速度呈现平滑程度
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//清空画布并以透明背景色填充
g.Clear(System.Drawing.Color.Transparent);
//在指定位置并且按指定大小绘制原图片的指定部分
g.DrawImage(serverImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
new System.Drawing.Rectangle(x, y, ow, oh),
System.Drawing.GraphicsUnit.Pixel);
try
{
//以jpg格式保存缩略图
bm.Save(thumbnailImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (System.Exception e)
{
throw e;
}
finally
{
serverImage.Dispose();
bm.Dispose();
g.Dispose();
}
}
}
}