页面代码
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="aaa.aspx.cs" Inherits="aaa" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> </head> <body> <form id="form1" runat="server"> <asp:FileUpload ID="FileUpload1" runat="server" accept=".jpg,.png,.jpeg" /><%--只能上传jpg格式 png格式 jpeg格式--%> <asp:Button ID="Button1" runat="server" Text="上传" /> <asp:Image ID="Image1" runat="server" /><%--用于将上传的图片加上水印效果展示在网页上出来--%> </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 System.Drawing;//加水印要先引用这个命名空间 public partial class aaa : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Button1.Click += Button1_Click; } //上传按钮的点击事件 void Button1_Click(object sender, EventArgs e) { //如果没有选中文件跳走不走下面的代码 if (!FileUpload1.HasFile) return; //获取要加水印的上传图片 要加水印的图片来自于FileUpload1.FileContent里 System.Drawing.Image img = System.Drawing.Image.FromStream(FileUpload1.FileContent); //创建一个画画类 用它进行画画 将要画的图片放到里面 Graphics g = Graphics.FromImage(img); //往图片里加文字 string s = "123呵呵呵"; //用黑体大小20px的字体来画 Font f = new Font("黑体", 20); // 创建一个画刷 实线的 颜色红色 SolidBrush实线 Brush b = new SolidBrush(Color.Red); //从图片的左边的横向10px和纵向10px开始画 PointF p = new PointF(10, 10); //g下面的画字符串 需要四个参数 (需要画什么东西,东西的字体大小,需要用什么画笔画画出来什么颜色,从什么位置画) //将设置的参数s f b p放到里面 g.DrawString(s, f, b, p); //获取要保存图片的相对路径 string path = "uploads/" + DateTime.Now.ToString("yyyyMMddHHmmssms") + FileUpload1.FileName; //将图片保存到绝对路径 img.Save(Server.MapPath(path)); //将图片展示出来 Image1.ImageUrl = path; } }
效果
往图片里加水印图片
页面代码一样
右键查看代买
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Drawing; public partial class aaa : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Button1.Click += Button1_Click; } void Button1_Click(object sender, EventArgs e) { if (!FileUpload1.HasFile) return; System.Drawing.Image img = System.Drawing.Image.FromStream(FileUpload1.FileContent); Graphics g = Graphics.FromImage(img); PointF p = new PointF(10, 10); //System.Drawing.Image.FromFile(Server.MapPath("uploads/222.png"))获取要加入图片的路径 g.DrawImage(System.Drawing.Image.FromFile(Server.MapPath("uploads/222.png")), p); string path = "uploads/" + DateTime.Now.ToString("yyyyMMddHHmmssms") + FileUpload1.FileName; img.Save(Server.MapPath(path)); Image1.ImageUrl = path; } }
效果