您的位置:首页 > 其它

图片上传加水印验证码

2015-06-02 10:31 127 查看

文件上传:

把相对路径变成绝对路径。

string absolutePath = Server.MapPath(relativePath);


FileUpload控件:

属性:

FileName:文件名

HasFile:bool 是否选中了文件

FileBytes:要上传文件的二进制数据

方法:

SaveAs(string 绝对路径):上传,另存为。


一、上传到硬盘文件夹

(一)传单个文件
第一步:准备好文件及路径:
//把之前在客户端的文件名给取出来
string fileName = FileUpload1.FileName;

//防止文件重名
fileName = DateTime.Now.ToString("yyyyMMddhhmmssms") + fileName;

//把相对路径转化为绝对路径
string path = Server.MapPath("uploads/" + fileName);

第二步:执行上传:
//上传
FileUpload1.SaveAs(path);   //参数必须根路径


注意:

1.如何防止文件重名?(加时间)

2.如何防止同一时间点不同用户传统一文件名?(加用户名)


(二)传多个文件:
思路:遍历表单中所有的FileUpload控件,如果选择文件就上传

int index = 0;
foreach (Control ctrl in form1.Controls)
{
if (ctrl is FileUpload)
{
index++;
//取得每个上传控件
FileUpload upload = ctrl as FileUpload;
//上传控件中选上文件了
if (upload.HasFile)
{
//做文件路径出来
string path = Server.MapPath("uploads/" + DateTime.Now.ToString("yyyyMMddhhmmss") + index.ToString("00") + upload.FileName);

//上传
upload.SaveAs(path);
}
}
}

二、上传到数据库Image字段:

(一)传到数据库去
1.做数据库的操作代码。DA Data


Image字段对应在程序里是byte[]类型


2.做界面上的代码。


a.把界面的值取出来

FileUpload1.FileBytes - 用来获得上传文件的二进制数据。

b.送到数据库去


(二)从数据库中找出来,显示出来

法一:会生成垃圾文件

在服务端生成一个JPG,把这个JPG的路径赋给Image控件

法二:单独做一个用来显示图片二进制数据的页面。把这个页面赋给Image控件。

加水印

------------------------------------


上传图片加水印:

//一、从上传数据中,转化成图片对象。
Stream s = FileUpload1.FileContent;
System.Drawing.Image img = System.Drawing.Image.FromStream(s);

//二、对图片对象进行画水印
//1.造笔
SolidBrush brush = new SolidBrush(Color.Yellow);
//2.造字体
Font font = new Font("Comic Sans MS", 18);
//3.找到图像绘图区域
Graphics g = Graphics.FromImage(img);
g.DrawString("http://www.itNBA.com", font, brush, 0, 0);

//三、图片对象另存到硬盘上去
string fileName = FileUpload1.FileName;
string path = Server.MapPath("uploads/" + fileName);
img.Save(path);

验证码

public partial class 验证码 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillYZM();
}
}
private void fillYZM() {
Bitmap img = new Bitmap(80,30);
SolidBrush bi = new SolidBrush(Color.Black);
Font font = new Font("新宋体", 24);
Graphics g = Graphics.FromImage(img);
g.FillRectangle(bi, 0, 0, img.Width, img.Height);
bi.Color = Color.White;

g.DrawString(Get(), font, bi, 0, 0);
string  path = Server.MapPath("temp.jpg");
img.Save(path);

Image1.ImageUrl = "temp.jpg";
}
private string Get()
{
string s="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random rand = new Random();
string yzm = "";
for (int i = 0; i < 4; i++)
{
int st=rand.Next(s.Length);
yzm += s.Substring(st, 1);
}
Session["yzm"] = yzm;
return yzm;

}
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text.Equals(Session["yzm"].ToString()))
{
Literal1.Text = "<script>alert('验证码输入正确!');</script>";
}
else
{
Literal1.Text = "<script>alert('验证码输入不正确!');</script>";
}
}

protected void Image1_Init(object sender, EventArgs e)
{

}

protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
fillYZM();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: