<%@ 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>

[CODE]

csharp

using System;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Text;

using System.Text.RegularExpressions;

using System.Drawing;

using System.Drawing.Imaging;

using System.Collections;

using System.ComponentModel;

namespace Legalsoft.Images

{

/// <summary>

/// News 的摘要说明

/// </summary>

public class XImage

{

public Color tBackground;

public Color tBorder;

public Color tShadow;

public int tQuality;

public string markPosition;

/// <summary>

/// 图片参数预定义

/// </summary>

static Hashtable htmimes = new Hashtable();

internal readonly string AllowExt = “.jpe|.jpeg|.jpg|.png|.tif|.tiff|.bmp|.gif“;

public XImage()

{

tBackground = Color.Transparent;

tBorder = Color.Transparent;

tShadow = Color.Transparent;

tQuality = 100;

markPosition = “左下角“;

#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“;

htmimes[“.gif“] = “image/gif“;

#endregion

}

#region 下载指定URL图片并保存

/// <summary>

/// 下载指定URL的文件并保存到指定目录

/// </summary>

/// <param name=“strUrl“></param>

public void DownloadImage(string strUrl, string file)

{

System.Net.WebClient wc = new System.Net.WebClient();

wc.DownloadFile(strUrl, file);

}

#endregion

#region C#自动生成缩略图

/// <summary>

/// 按给定名字确定颜色

/// </summary>

/// <param name=“name“></param>

/// <returns></returns>

public Color ToColor(string name)

{

if (name == “白色“) return Color.White;

if (name == “红色“) return Color.Red;

if (name == “蓝色“) return Color.Blue;

if (name == “绿色“) return Color.Green;

if (name == “黑色“) return Color.Black;

if (name == “灰色“) return Color.DarkGray;

if (name == “黄色“) return Color.Yellow;

if (name == “紫色“) return Color.Cyan;

if (name == “无色“) return Color.Transparent;

return Color.Transparent;

}

/// <summary>

/// 按名字设置各种颜色,可以自行扩充:)

/// </summary>

/// <param name=“name“></param>

/// <returns></returns>

public int ToQuality(string name)

{

return Int32.Parse(name.Replace(“%“, ““));

}

/// <summary>

/// 获取图像编码解码器的所有相关信息

/// </summary>

/// <param name=“mimeType“>包含编码解码器的多用途网际邮件扩充协议 (MIME) 类型的字符串</param>

/// <returns>返回图像编码解码器的所有相关信息</returns>

private 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>

private 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>

private void SaveImage(System.Drawing.Image image, string savePath, ImageCodecInfo ici)

{

//设置 原图片 对象的 EncoderParameters 对象

EncoderParameters parameters = new EncoderParameters(1);

parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, ((long)tQuality));

image.Save(savePath, ici, parameters);

parameters.Dispose();

}

/// <summary>

/// 生成缩略图

/// </summary>

/// <param name=“sourceImagePath“>原图片路径(相对路径)</param>

/// <param name=“thumbnailImagePath“>生成的缩略图路径,如果为空则保存为原图片路径(相对路径)</param>

/// <param name=“thumbnailImageWidth“>缩略图的宽度(高度与按源图片比例自动生成)</param>

public void ToThumbnail(string sourceImagePath, string
thumbnailImagePath, int thumbnailImageWidth, int thumbnailImageHeight )

{

// 1.先检查图片格式等信息

string ThumbnailImagePath = thumbnailImagePath;

string SourceImagePath = sourceImagePath;

string sExt = SourceImagePath.Substring(SourceImagePath.LastIndexOf(“.“)).ToLower();

if (SourceImagePath.ToString() == System.String.Empty)

{

throw new NullReferenceException(“SourceImagePath is null!“);

}

if (!CheckValidExt(sExt))

{

throw new ArgumentException(“原图片文件格式不正确,支持的格式有[ “ + AllowExt + “ ]“, “SourceImagePath“);

}

// 从原图片创建 Image 对象

System.Drawing.Image image = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(SourceImagePath));

// 2.计算图片的位置、尺寸等信息

int tWidth, tHeight, tLeft, tTop;

double fScale = (double)thumbnailImageHeight / (double)thumbnailImageWidth; // 高度宽度比

if (((double)image.Width * fScale) > (double)image.Height) // 如果原图比较宽

{

tWidth = thumbnailImageWidth;

tHeight = (int)((double)image.Height * (double)tWidth / (double)image.Width);

tLeft = 0;

tTop = (thumbnailImageHeight-tHeight)/2;

}

else

{

tHeight = thumbnailImageHeight;

tWidth = (int)((double)image.Width * (double)tHeight / (double)image.Height);

tLeft = (thumbnailImageWidth-tWidth)/2;

tTop = 0;

}

if (tLeft < 0) tLeft = 0;

if (tTop < 0) tTop = 0;

if (tBorder != Color.Transparent)

{

tWidth -= 2;

tHeight -= 2;

tLeft++;

tTop++;

}

if (tShadow != Color.Transparent)

{

tWidth -= 1;

tHeight -= 1;

}

//用指定的大小和格式初始化 Bitmap 类的新实例

//Bitmap bitmap = new Bitmap(ThumbnailImageWidth, num, PixelFormat.Format32bppArgb);

Bitmap bitmap = new Bitmap(thumbnailImageWidth, thumbnailImageHeight, PixelFormat.Format32bppArgb);

//从指定的 Image 对象创建新 Graphics 对象

Graphics graphics = Graphics.FromImage(bitmap);

//清除整个绘图面并以透明背景色填充

if (tBackground != Color.Transparent)

{

graphics.Clear(tBackground);

}

else

{

graphics.Clear(Color.Transparent);

}

// 添加阴影

if (tShadow != Color.Transparent)

{

Pen shPen = new Pen(tShadow);

graphics.DrawLine(shPen, new Point(1,
thumbnailImageHeight-1), new Point(thumbnailImageWidth-1,
thumbnailImageHeight-1));

graphics.DrawLine(shPen, new
Point(thumbnailImageWidth-1, 1), new Point(thumbnailImageWidth-1,
thumbnailImageHeight-1));

}

// 添加边框

if (tBorder != Color.Transparent)

{

Pen bdPen = new Pen(tBorder);

if (tShadow != Color.Transparent)

{

graphics.DrawRectangle(bdPen, new Rectangle(0, 0, thumbnailImageWidth-2, thumbnailImageHeight-2));

}

else

{

graphics.DrawRectangle(bdPen, new Rectangle(0, 0, thumbnailImageWidth-1, thumbnailImageHeight-1));

}

}

//在指定位置并且按指定大小绘制 原图片 对象

graphics.DrawImage(image, new Rectangle(tLeft, tTop, tWidth, tHeight));

image.Dispose();

try

{

//将此 原图片 以指定格式并用指定的编解码参数保存到指定文件

string savepath = (ThumbnailImagePath == null ? SourceImagePath : ThumbnailImagePath);

SaveImage(bitmap, HttpContext.Current.Server.MapPath(savepath), GetCodecInfo((string)htmimes[sExt]));

}

catch (System.Exception e)

{

throw e;

}

finally

{

bitmap.Dispose();

graphics.Dispose();

}

}

#endregion

#region C#给图片添加水印

public void Mark(string sourceImagePath, string markString)

{

// 1.先检查图片格式等信息

string markImagePath = sourceImagePath;

string SourceImagePath = sourceImagePath;

string sExt = SourceImagePath.Substring(SourceImagePath.LastIndexOf(“.“)).ToLower();

if (SourceImagePath.ToString() == System.String.Empty)

{

throw new NullReferenceException(“SourceImagePath is null!“);

}

if (!CheckValidExt(sExt))

{

throw new ArgumentException(“原图片文件格式不正确,支持的格式有[ “ + AllowExt + “ ]“, “SourceImagePath“);

}

// 从原图片创建 Image 对象

System.Drawing.Image image = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(SourceImagePath));

//用指定的大小和格式初始化 Bitmap 类的新实例

Bitmap bitmap = new Bitmap(image.Width, image.Height, PixelFormat.Format32bppArgb);

//从指定的 Image 对象创建新 Graphics 对象

Graphics graphics = Graphics.FromImage(bitmap);

//在指定位置并且按指定大小绘制 原图片 对象

graphics.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height));

#region 绘制水印

// 设置水印字体

int fHeight = image.Height/5;

if(fHeight>16) fHeight = 16;

Font drawFont = new Font(“Arial“, fHeight);

// 设置水印文字位置,默认为左下角

float x = 4;

float y = image.Height - drawFont.Height - 4;

if (markPosition == “左上角“)

{

y = 4;

}

if (markPosition == “右上角“)

{

x = image.Width - markString.Length * fHeight / 2 - fHeight;

y = 4;

}

if (markPosition == “右下角“)

{

x = image.Width - markString.Length * fHeight / 2 - fHeight;

}

if (markPosition == “图片中间“)

{

x = image.Width / 2 - markString.Length * fHeight / 2;

y = image.Height / 2 - fHeight / 2;

}

StringFormat drawFormat = new StringFormat();

drawFormat.FormatFlags = StringFormatFlags.NoWrap;

// 设置水印文字颜色,先绘制一个黑色字作为阴影,再绘制白色字,这样比较显眼;

SolidBrush drawBrush = new SolidBrush(Color.Black);

graphics.DrawString(markString, drawFont, drawBrush, x, y, drawFormat);

drawBrush.Color = Color.White;

graphics.DrawString(markString, drawFont, drawBrush, x-1, y-1, drawFormat);

#endregion

image.Dispose();

try

{

//将此 原图片 以指定格式并用指定的编解码参数保存到指定文件

string savepath = SourceImagePath;

SaveImage(bitmap, HttpContext.Current.Server.MapPath(savepath), GetCodecInfo((string)htmimes[sExt]));

}

catch (System.Exception e)

{

throw e;

}

finally

{

bitmap.Dispose();

graphics.Dispose();

}

}

#endregion

}

}

[原创]超强C#图片上传,加水印,自动生成缩略图源代码的更多相关文章

  1. java图片处理(加水印、生成缩略图)等之Thumbnailator库

    Thumbnailator 是一个为Java界面更流畅的缩略图生成库.从API提供现有的图像文件和图像对象的缩略图中简化了缩略过程,两三行代码就能够从现有图片生成缩略图,且允许微调缩略图生成,同时保持 ...

  2. ThinkPHP5+Layui实现图片上传加预览

    html代码 <div class="layui-upload"> <button type="button" class="lay ...

  3. 黄聪:C#图片处理封装类(裁剪、缩放、清晰度、加水印、生成缩略图)有示例(转)

    C#图片处理示例(裁剪,缩放,清晰度,水印) 吴剑 2011-02-20 原创文章,转载必需注明出处:http://www.cnblogs.com/wu-jian/ 前言 需求源自项目中的一些应用,比 ...

  4. 七牛上传ipa后自动生成plist文件

    1.利用模板技术动态生成plist文件的内容:(模板内容和data替换为plist需要的内容) //artTemplate <script src="js/template.js&qu ...

  5. 小程序OSS图片上传

    图片上传加水印问题,代码如下! chooseImage: function (e) { var that = this; wx.chooseImage({ sizeType: ['original', ...

  6. 修改DedeCMS图片上传路径命名规则的具体方法步骤

    收藏到:0时间:2013-08-23   文章来源:马海祥博客   访问次数:2350 最近在整理网站根目录下文件的时候,发现马海祥博客网站已经有上千个文件夹了,其中光图片文件夹就占了近一半.这个主要 ...

  7. [前端 4] 使用Js实现图片上传预览

    导读:今天做图片上传预览,刚开始的做法是,先将图片上传到Nginx,然后重新加载页面才能看到这个图片.在这个过程中,用户一直都看不到自己上传的文件是什么样子.Ps:我发现我真的有强迫症了,都告诉我说不 ...

  8. elementUI 图片上传限制上传图片的宽高

    文件上传,需当上传的文件类型为图片的时候,需要限制图片的宽高. 此处采用了new Promise异步加载的方式,等图片上传加载完成后, 页面代码: <el-form-item label=&qu ...

  9. ThinkPHP示例:图片上传

    ThinkPHP示例之图片上传,包括图片上传.数据库保存.缩略图生成以及图片水印功能演示.首先需要下载框架核心,然后把示例解压到Web根目录下面,并修改入口文件中的框架入口文件的位置.导入示例目录下面 ...

随机推荐

  1. JNI之数组

    Array Operations -- 数组操作 1.GetArrayLength jsize GetArrayLength(JNIEnv *env, jarray array); Returns t ...

  2. Android Studio 下使用git -- 个人,本地版本控制

    第一步:下载安装git 下载地址 : https://git-scm.com/downloads 第二步:Android Studio 下配置git路径. 配置之后,Test弹出如下成功的提示即可. ...

  3. 安网讯通签约孟强美容CRM

    整形美容CRM软件是辽宁安网讯通有限公司为孟强整形医院定制开发的一套客户关系管理软件,软件专门针对整形美容行业专科门诊的需求,能满足大中小整形美容机构或或各种专科科室的日常业务需求. 主要功能包括: ...

  4. [JQuery]用InsertAfter实现图片走马灯展示效果2——js代码重构

    写在前面 前面写过一篇文章<[JQuery]用InsertAfter实现图片走马灯展示效果>,自从写过那样的也算是使用面向对象的写法吧,代码实在丑陋,自从写过那样的代码,就是自己的一块心病 ...

  5. CSS3:图片水平垂直居中

    加上这两个就行 display:-webkit-box;     显示成盒子模式 -webkit-box-align:center;   垂直居中 -webkit-box-pack:center;   ...

  6. ExtJS 4 在Ext.tab.Panel中使用Ext.ux.IFrame打开url指向的网页

    ext-4.2.1.883\examples\ux\IFrame.js ext-4.2.1.883\examples\ux\TabCloseMenu.js 复制到 \Scripts\ext-4.2.1 ...

  7. ODATA4 及实现

    ODATA4 的JAVASCRIPT 实现:     http://jaydata.org/ ODATA4 的JAVA 项目  Apache Olingo:http://olingo.incubato ...

  8. PHP中使用XMLRPC

    PHP中简单使用XMLRPC,服务器端和客户端都为PHP代码实现. 这里使用的XML-RPC完整包括client和server的XML-RPC实现. 客户端和服务器端分别由 xmlrpc_client ...

  9. 判断浏览器是否支持 JS

    在有些浏览器中不支持(或者被禁用了)脚本语言,那么javascript脚本则无法被执行.但是用户并不知道浏览器是否支持,或者被禁用.我们可以通过<noscript>标签来告知用户,JS脚运 ...

  10. Sqoop操作实践

    Sqoop操作实践 @(Hadoop) Sqoop常用参命令 序号 命令/command 类 说明 1 impor ImportTool 从关系型数据库中导入数据(来自表或者查询语句)到HDFS中 2 ...