超强C#图片上传,加水印,自动生成缩略图源代码

                  北京联高软件开发有限公司倾情奉献经过测试的超强C#图片上传,加水印,自动生成缩略图源代码。可以指定水印位置、文字;可以设置缩略图背景颜色,边框及其颜色,阴影及其颜色;可以指定缩略图质量;支持GIF,JPEG,JPG,PNG,BMP,TIFF等多种格式图片文件。

原文地址 :http://www.cocsoft.cn/docs/docs/10/1000.html

<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Net" %>
<%@ Import NameSpace="System.Web" %>
<%@ Import NameSpace="Legalsoft.Images" %>
<script language="C#" runat="server">

protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
foreach (string f in Request.Files.AllKeys)
{
// 查找是否存在指定的目,如果允许创建目录,则创建之。
string f_path = TextBox1.Text;
if (!System.IO.Directory.Exists(Server.MapPath(f_path)))
{
if (CheckBox1.Checked)
{
System.IO.Directory.CreateDirectory(Server.MapPath(f_path));
}
else
{
return;
}
}
// 获取提交的文件名,包含的全部的目录信息;需要提取其文件名(名字+后缀)
HttpPostedFile file = Request.Files[f];
string fname = file.FileName.ToLower();
fname = fname.Replace("\\", "/");
int lsub = fname.LastIndexOf("/");
if (lsub >= 0)
{
fname = fname.Substring(lsub + 1, fname.Length - lsub - 1);
string[] fa_ext = fname.Split(".");
string f_pre = fa_ext[fa_ext.Length - 2];
string f_ext = fa_ext[fa_ext.Length - 1];
if (f_ext == "gif" || f_ext == "jpg" || f_ext == "jpeg")
{
file.SaveAs(Server.MapPath(f_path) + "/" + f_pre + "." + f_ext);

XImage img = new XImage();
// 添加水印
if (TextBox2.Text.Trim() != "")
{
img.markPosition = DropDownList5.Items[DropDownList5.SelectedIndex].Text;
img.Mark(f_path + f_pre + "." + f_ext, TextBox2.Text);
}

// 如果需要生成所略图
if (CheckBox2.Checked)
{
int tWidth = Int32.Parse(TextBox3.Text);
int tHeight = Int32.Parse(TextBox4.Text);
img.tBackground = img.ToColor(DropDownList1.Items[DropDownList1.SelectedIndex].Text);
img.tBorder = img.ToColor(DropDownList2.Items[DropDownList2.SelectedIndex].Text);
img.tShadow = img.ToColor(DropDownList3.Items[DropDownList3.SelectedIndex].Text);
img.tQuality = img.ToQuality(DropDownList4.Items[DropDownList4.SelectedIndex].Text);
img.ToThumbnail(f_path + f_pre + "." + f_ext, f_path + f_pre + "_thumb." + f_ext, tWidth, tHeight);
}
}
}
}
}
}

</script>

<!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 id="Head1" runat="server">
<title>C#图片上传及生成缩略图,添加水印的代码</title>
<meta name="keywords" content="C#文件上传的实例代码"/>
<meta name="description" content="在线式代码自动生成器SharpOnline只需要数据库Table定义就自动生成网站的全套C#源代码与页面(包括数据查询于操作、输入页面、编辑页面及其后台页面)。" />
<meta http-equiv="content-type" content="text/html; charset=gb2312"/>
<meta http-equiv="content-language" content="zh-cn"/>
<link href="/favicon.ico" type="image/x-icon" rel="shortcut icon"/>
<link href="/favicon.ico" type="image/x-icon" rel="bookmark"/>
<meta http-equiv="imagetoolbar" content="no"/>
<meta name="distribution" content="global"/>
<link href="/common/style.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<form id="form1" runat="server">
<center>

<div style="width:938px;background-color:#FFFFFF;">

<table width="938" style="background-color:#F0F0FF;padding:8px;line-height:24px;text-align:left;" cellpadding="0" cellspacing="0">
<tr>
<td align="right">保存的目录:</td>
<td>
<asp:TextBox ID="TextBox1" runat="server">/UploadedFiles/</asp:TextBox>
<asp:CheckBox ID="CheckBox1" runat="server" Checked="true" />自动创建目录
</td>
</tr>
<tr>
<td align="right">添加水印字:</td>
<td>
文字:<asp:TextBox ID="TextBox2" runat="server">50018.COM</asp:TextBox> (可以为空,则不加水印)<br />
位置:
<asp:DropDownList ID="DropDownList5" runat="server">
<asp:ListItem Selected="True">左下角</asp:ListItem>
<asp:ListItem>左上角</asp:ListItem>
<asp:ListItem>右下角</asp:ListItem>
<asp:ListItem>右上角</asp:ListItem>
<asp:ListItem>图片中间</asp:ListItem>
</asp:DropDownList><br />
</td>
</tr>
<tr>
<td align="right">生成缩略图:</td>
<td>
<asp:CheckBox ID="CheckBox2" Checked="true" runat="server" />生成缩略图<br />
宽度: <asp:TextBox ID="TextBox3" runat="server">100</asp:TextBox><br />
高度: <asp:TextBox ID="TextBox4" runat="server">75</asp:TextBox><br />
背景:
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Selected="True">无色</asp:ListItem>
<asp:ListItem>白色</asp:ListItem>
<asp:ListItem>红色</asp:ListItem>
<asp:ListItem>蓝色</asp:ListItem>
<asp:ListItem>黄色</asp:ListItem>
<asp:ListItem>黑色</asp:ListItem>
<asp:ListItem>绿色</asp:ListItem>
<asp:ListItem>紫色</asp:ListItem>
<asp:ListItem>灰色</asp:ListItem>
</asp:DropDownList><br />
边框:
<asp:DropDownList ID="DropDownList2" runat="server">
<asp:ListItem Selected="True">无色</asp:ListItem>
<asp:ListItem>白色</asp:ListItem>
<asp:ListItem>红色</asp:ListItem>
<asp:ListItem>蓝色</asp:ListItem>
<asp:ListItem>黄色</asp:ListItem>
<asp:ListItem>黑色</asp:ListItem>
<asp:ListItem>绿色</asp:ListItem>
<asp:ListItem>紫色</asp:ListItem>
<asp:ListItem>灰色</asp:ListItem>
</asp:DropDownList><br />
阴影:
<asp:DropDownList ID="DropDownList3" runat="server">
<asp:ListItem Selected="True">无色</asp:ListItem>
<asp:ListItem>白色</asp:ListItem>
<asp:ListItem>红色</asp:ListItem>
<asp:ListItem>蓝色</asp:ListItem>
<asp:ListItem>黄色</asp:ListItem>
<asp:ListItem>黑色</asp:ListItem>
<asp:ListItem>绿色</asp:ListItem>
<asp:ListItem>紫色</asp:ListItem>
<asp:ListItem>灰色</asp:ListItem>
</asp:DropDownList><br />
质量:
<asp:DropDownList ID="DropDownList4" runat="server">
<asp:ListItem Selected="True">100%</asp:ListItem>
<asp:ListItem>90%</asp:ListItem>
<asp:ListItem>80%</asp:ListItem>
<asp:ListItem>60%</asp:ListItem>
<asp:ListItem>50%</asp:ListItem>
<asp:ListItem>40%</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td align="right">请选择文件:</td>
<td><asp:FileUpload ID="FileUpload1" runat="server" /></td>
</tr>
<tr>
<td align="right"></td>
<td><asp:Button ID="Button2" runat="server" Text="提交" Width="88px" /></td>
</tr>
</table>

</div>

</center>
</form>
</body>
</html>

  1. using System;   
  2. using System.Data;   
  3. using System.Data.SqlClient;   
  4. using System.Configuration;   
  5. using System.Web;   
  6. using System.Web.Security;   
  7. using System.Web.UI;   
  8. using System.Web.UI.WebControls;   
  9. using System.Web.UI.WebControls.WebParts;   
  10. using System.Web.UI.HtmlControls;   
  11. using System.Text;   
  12. using System.Text.RegularExpressions;   
  13. using System.Drawing;   
  14. using System.Drawing.Imaging;   
  15. using System.Collections;   
  16. using System.ComponentModel;   
  17. namespace Legalsoft.Images   
  18. {   
  19.     /// <summary>   
  20.     /// News 的摘要说明   
  21.     /// </summary>   
  22.     public class XImage   
  23.     {   
  24.         public Color tBackground;   
  25.         public Color tBorder;   
  26.         public Color tShadow;   
  27.         public int tQuality;   
  28.         public string markPosition;   
  29.         /// <summary>   
  30.         /// 图片参数预定义   
  31.         /// </summary>   
  32.         static Hashtable htmimes = new Hashtable();   
  33.         internal readonly string AllowExt = ".jpe|.jpeg|.jpg|.png|.tif|.tiff|.bmp|.gif";   
  34.         public XImage()   
  35.         {   
  36.             tBackground = Color.Transparent;   
  37.             tBorder = Color.Transparent;   
  38.             tShadow = Color.Transparent;   
  39.             tQuality = 100;   
  40.             markPosition = "左下角";  
  41.             #region 图片类型预定义   
  42.             htmimes[".jpe"]="image/jpeg";   
  43.             htmimes[".jpeg"] = "image/jpeg";   
  44.             htmimes[".jpg"] = "image/jpeg";   
  45.             htmimes[".png"] = "image/png";   
  46.             htmimes[".tif"] = "image/tiff";   
  47.             htmimes[".tiff"] = "image/tiff";   
  48.             htmimes[".bmp"] = "image/bmp";   
  49.             htmimes[".gif"] = "image/gif";  
  50.             #endregion    
  51.         }  
  52.         #region 下载指定URL图片并保存   
  53.         /// <summary>   
  54.         /// 下载指定URL的文件并保存到指定目录   
  55.         /// </summary>   
  56.         /// <param name="strUrl"></param>   
  57.         public void DownloadImage(string strUrl, string file)   
  58.         {   
  59.             System.Net.WebClient wc = new System.Net.WebClient();   
  60.             wc.DownloadFile(strUrl, file);   
  61.         }  
  62.         #endregion  
  63.         #region C#自动生成缩略图   
  64.         /// <summary>   
  65.         /// 按给定名字确定颜色   
  66.         /// </summary>   
  67.         /// <param name="name"></param>   
  68.         /// <returns></returns>   
  69.         public Color ToColor(string name)   
  70.         {   
  71.             if (name == "白色"return Color.White;   
  72.             if (name == "红色"return Color.Red;   
  73.             if (name == "蓝色"return Color.Blue;   
  74.             if (name == "绿色"return Color.Green;   
  75.             if (name == "黑色"return Color.Black;   
  76.             if (name == "灰色"return Color.DarkGray;   
  77.             if (name == "黄色"return Color.Yellow;   
  78.             if (name == "紫色"return Color.Cyan;   
  79.             if (name == "无色"return Color.Transparent;   
  80.             return Color.Transparent;   
  81.         }   
  82.         /// <summary>   
  83.         /// 按名字设置各种颜色,可以自行扩充:)   
  84.         /// </summary>   
  85.         /// <param name="name"></param>   
  86.         /// <returns></returns>   
  87.         public int ToQuality(string name)   
  88.         {   
  89.             return Int32.Parse(name.Replace("%"""));   
  90.         }   
  91.         /// <summary>    
  92.         /// 获取图像编码解码器的所有相关信息    
  93.         /// </summary>    
  94.         /// <param name="mimeType">包含编码解码器的多用途网际邮件扩充协议 (MIME) 类型的字符串</param>    
  95.         /// <returns>返回图像编码解码器的所有相关信息</returns>    
  96.         private static ImageCodecInfo GetCodecInfo(string mimeType)   
  97.         {   
  98.             ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();   
  99.             foreach (ImageCodecInfo ici in CodecInfo)   
  100.             {   
  101.                 if (ici.MimeType == mimeType) return ici;   
  102.             }   
  103.             return null;   
  104.         }   
  105.         /// <summary>    
  106.         /// 检测扩展名的有效性    
  107.         /// </summary>    
  108.         /// <param name="sExt">文件名扩展名</param>    
  109.         /// <returns>如果扩展名有效,返回true,否则返回false.</returns>    
  110.         private bool CheckValidExt(string sExt)   
  111.         {   
  112.             bool flag = false;   
  113.             string[] aExt = AllowExt.Split("|");   
  114.             foreach (string filetype in aExt)   
  115.             {   
  116.                 if (filetype.ToLower() == sExt)   
  117.                 {   
  118.                     flag = true;   
  119.                     break;   
  120.                 }   
  121.             }   
  122.             return flag;   
  123.         }   
  124.         /// <summary>    
  125.         /// 保存图片    
  126.         /// </summary>    
  127.         /// <param name="image">Image 对象</param>    
  128.         /// <param name="savePath">保存路径</param>    
  129.         /// <param name="ici">指定格式的编解码参数</param>    
  130.         private void SaveImage(System.Drawing.Image image, string savePath, ImageCodecInfo ici)   
  131.         {   
  132.             //设置 原图片 对象的 EncoderParameters 对象    
  133.             EncoderParameters parameters = new EncoderParameters(1);   
  134.             parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, ((long)tQuality));   
  135.             image.Save(savePath, ici, parameters);   
  136.             parameters.Dispose();   
  137.         }   
  138.         /// <summary>    
  139.         /// 生成缩略图    
  140.         /// </summary>    
  141.         /// <param name="sourceImagePath">原图片路径(相对路径)</param>    
  142.         /// <param name="thumbnailImagePath">生成的缩略图路径,如果为空则保存为原图片路径(相对路径)</param>    
  143.         /// <param name="thumbnailImageWidth">缩略图的宽度(高度与按源图片比例自动生成)</param>    
  144.         public void ToThumbnail(string sourceImagePath, string thumbnailImagePath, int thumbnailImageWidth, int thumbnailImageHeight )   
  145.         {   
  146.             // 1.先检查图片格式等信息   
  147.             string ThumbnailImagePath = thumbnailImagePath;   
  148.             string SourceImagePath = sourceImagePath;   
  149.             string sExt = SourceImagePath.Substring(SourceImagePath.LastIndexOf(".")).ToLower();   
  150.             if (SourceImagePath.ToString() == System.String.Empty)   
  151.             {   
  152.                 throw new NullReferenceException("SourceImagePath is null!");   
  153.             }   
  154.             if (!CheckValidExt(sExt))   
  155.             {   
  156.                 throw new ArgumentException("原图片文件格式不正确,支持的格式有[ " + AllowExt + " ]""SourceImagePath");   
  157.             }   
  158.             // 从原图片创建 Image 对象    
  159.             System.Drawing.Image image = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(SourceImagePath));   
  160.             // 2.计算图片的位置、尺寸等信息   
  161.             int tWidth, tHeight, tLeft, tTop;   
  162.             double fScale = (double)thumbnailImageHeight / (double)thumbnailImageWidth; // 高度宽度比   
  163.             if (((double)image.Width * fScale) > (double)image.Height) // 如果原图比较宽   
  164.             {   
  165.                 tWidth = thumbnailImageWidth;   
  166.                 tHeight = (int)((double)image.Height * (double)tWidth / (double)image.Width);   
  167.                 tLeft = 0;   
  168.                 tTop = (thumbnailImageHeight-tHeight)/2;   
  169.             }   
  170.             else  
  171.             {   
  172.                 tHeight = thumbnailImageHeight;   
  173.                 tWidth = (int)((double)image.Width * (double)tHeight / (double)image.Height);   
  174.                 tLeft = (thumbnailImageWidth-tWidth)/2;   
  175.                 tTop = 0;   
  176.             }   
  177.             if (tLeft < 0) tLeft = 0;   
  178.             if (tTop < 0) tTop = 0;   
  179.             if (tBorder != Color.Transparent)   
  180.             {   
  181.                 tWidth -= 2;   
  182.                 tHeight -= 2;   
  183.                 tLeft++;   
  184.                 tTop++;   
  185.             }   
  186.             if (tShadow != Color.Transparent)   
  187.             {   
  188.                 tWidth -= 1;   
  189.                 tHeight -= 1;   
  190.             }   
  191.             //用指定的大小和格式初始化 Bitmap 类的新实例    
  192.             //Bitmap bitmap = new Bitmap(ThumbnailImageWidth, num, PixelFormat.Format32bppArgb);   
  193.             Bitmap bitmap = new Bitmap(thumbnailImageWidth, thumbnailImageHeight, PixelFormat.Format32bppArgb);   
  194.             //从指定的 Image 对象创建新 Graphics 对象    
  195.             Graphics graphics = Graphics.FromImage(bitmap);   
  196.             //清除整个绘图面并以透明背景色填充   
  197.             if (tBackground != Color.Transparent)   
  198.             {   
  199.                 graphics.Clear(tBackground);   
  200.             }   
  201.             else  
  202.             {   
  203.                 graphics.Clear(Color.Transparent);   
  204.             }   
  205.             // 添加阴影   
  206.             if (tShadow != Color.Transparent)   
  207.             {   
  208.                 Pen shPen = new Pen(tShadow);   
  209.                 graphics.DrawLine(shPen, new Point(1, thumbnailImageHeight-1), new Point(thumbnailImageWidth-1, thumbnailImageHeight-1));   
  210.                 graphics.DrawLine(shPen, new Point(thumbnailImageWidth-1, 1), new Point(thumbnailImageWidth-1, thumbnailImageHeight-1));   
  211.             }   
  212.             // 添加边框   
  213.             if (tBorder != Color.Transparent)   
  214.             {   
  215.                 Pen bdPen = new Pen(tBorder);   
  216.                 if (tShadow != Color.Transparent)   
  217.                 {   
  218.                     graphics.DrawRectangle(bdPen, new Rectangle(0, 0, thumbnailImageWidth-2, thumbnailImageHeight-2));   
  219.                 }   
  220.                 else  
  221.                 {   
  222.                     graphics.DrawRectangle(bdPen, new Rectangle(0, 0, thumbnailImageWidth-1, thumbnailImageHeight-1));   
  223.                 }   
  224.             }   
  225.             //在指定位置并且按指定大小绘制 原图片 对象    
  226.             graphics.DrawImage(image, new Rectangle(tLeft, tTop, tWidth, tHeight));   
  227.             image.Dispose();   
  228.             try  
  229.             {   
  230.                 //将此 原图片 以指定格式并用指定的编解码参数保存到指定文件    
  231.                 string savepath = (ThumbnailImagePath == null ? SourceImagePath : ThumbnailImagePath);   
  232.                 SaveImage(bitmap, HttpContext.Current.Server.MapPath(savepath), GetCodecInfo((string)htmimes[sExt]));   
  233.             }   
  234.             catch (System.Exception e)   
  235.             {   
  236.                 throw e;   
  237.             }   
  238.             finally  
  239.             {   
  240.                 bitmap.Dispose();   
  241.                 graphics.Dispose();   
  242.             }   
  243.         }  
  244.         #endregion  
  245.         #region C#给图片添加水印   
  246.         public void Mark(string sourceImagePath, string markString)   
  247.         {   
  248.             // 1.先检查图片格式等信息   
  249.             string markImagePath = sourceImagePath;   
  250.             string SourceImagePath = sourceImagePath;   
  251.             string sExt = SourceImagePath.Substring(SourceImagePath.LastIndexOf(".")).ToLower();   
  252.             if (SourceImagePath.ToString() == System.String.Empty)   
  253.             {   
  254.                 throw new NullReferenceException("SourceImagePath is null!");   
  255.             }   
  256.             if (!CheckValidExt(sExt))   
  257.             {   
  258.                 throw new ArgumentException("原图片文件格式不正确,支持的格式有[ " + AllowExt + " ]""SourceImagePath");   
  259.             }   
  260.             // 从原图片创建 Image 对象    
  261.             System.Drawing.Image image = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(SourceImagePath));   
  262.             //用指定的大小和格式初始化 Bitmap 类的新实例    
  263.             Bitmap bitmap = new Bitmap(image.Width, image.Height, PixelFormat.Format32bppArgb);   
  264.             //从指定的 Image 对象创建新 Graphics 对象    
  265.             Graphics graphics = Graphics.FromImage(bitmap);   
  266.             //在指定位置并且按指定大小绘制 原图片 对象    
  267.             graphics.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height));  
  268.             #region 绘制水印   
  269.             // 设置水印字体   
  270.             int fHeight = image.Height/5;   
  271.             if(fHeight>16) fHeight = 16;   
  272.             Font drawFont = new Font("Arial", fHeight);   
  273.             // 设置水印文字位置,默认为左下角   
  274.             float x = 4;   
  275.             float y = image.Height - drawFont.Height - 4;   
  276.             if (markPosition == "左上角")   
  277.             {   
  278.                 y = 4;   
  279.             }   
  280.             if (markPosition == "右上角")   
  281.             {   
  282.                 x = image.Width - markString.Length * fHeight / 2 - fHeight;   
  283.                 y = 4;   
  284.             }   
  285.             if (markPosition == "右下角")   
  286.             {   
  287.                 x = image.Width - markString.Length * fHeight / 2 - fHeight;   
  288.             }   
  289.             if (markPosition == "图片中间")   
  290.             {   
  291.                 x = image.Width / 2 - markString.Length * fHeight / 2;   
  292.                 y = image.Height / 2 - fHeight / 2;   
  293.             }   
  294.             StringFormat drawFormat = new StringFormat();   
  295.             drawFormat.FormatFlags = StringFormatFlags.NoWrap;   
  296.             // 设置水印文字颜色,先绘制一个黑色字作为阴影,再绘制白色字,这样比较显眼;   
  297.             SolidBrush drawBrush = new SolidBrush(Color.Black);   
  298.             graphics.DrawString(markString, drawFont, drawBrush, x, y, drawFormat);   
  299.             drawBrush.Color = Color.White;   
  300.             graphics.DrawString(markString, drawFont, drawBrush, x-1, y-1, drawFormat);  
  301.             #endregion   
  302.             image.Dispose();   
  303.             try  
  304.             {   
  305.                 //将此 原图片 以指定格式并用指定的编解码参数保存到指定文件    
  306.                 string savepath = SourceImagePath;   
  307.                 SaveImage(bitmap, HttpContext.Current.Server.MapPath(savepath), GetCodecInfo((string)htmimes[sExt]));   
  308.             }   
  309.             catch (System.Exception e)   
  310.             {   
  311.                 throw e;   
  312.             }   
  313.             finally  
  314.             {   
  315.                 bitmap.Dispose();   
  316.                 graphics.Dispose();   
  317.             }   
  318.         }  
  319.         #endregion   
  320.     }   
  321. }  

posted @ 2008-12-24 20:20  funnyzak  阅读(498)  评论(0编辑  收藏  举报