您的位置:首页 > 其它

缩略图、水印、验证码

2016-01-07 15:36 323 查看
//////////////创建缩略图

//html

<form action="upload.ashx" method="post" enctype="multipart/form-data">

<input type="file" name="fileUpload" />

<input type="text" name="txtName" /><br />

<input type="submit" value="上传" />

</form>

//ashx

HttpPostedFile hpf = context.Request.Files["fileUpload"];

//获得文本框的值

string strName = context.Request.Form["txtName"];

//判断上传上来的文件大小

if (hpf.ContentLength > 0)

{

//获取文件在浏览器端的名字

//string fileName = System.IO.Path.GetFileName(hpf.FileName);

//获得文件后缀

string fileExtention = System.IO.Path.GetExtension(hpf.FileName);

//随机生成一个文件名

string fileName = DateTime.Now.ToShortDateString() + (new Random().Next(9999).ToString());

//拼接成完成的文件名

fileName = fileName + fileExtention;

//获得一个物理路径

string phyPath = context.Server.MapPath("upload/" + fileName);

//将文件保存到这个物理路径--------------------

hpf.SaveAs(phyPath);

//如果上传的是图片的话,就生成一张缩略图

if (hpf.ContentType.IndexOf("image") > -1)

{

//获得上传上来的图片

using (Image img = Bitmap.FromStream(hpf.InputStream))

{

//创建缩略图 对象

using (Bitmap thumbImg = new Bitmap(120, 30))

{

using (Graphics g = Graphics.FromImage(thumbImg))

{

//绘制缩略图:0,0,要将大图画成多大,要取大图的哪个部分,单位

g.DrawImage(img, new Rectangle(0, 0, thumbImg.Width, thumbImg.Height), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);

//生成 缩略图要保存的 物理位置

string thumbPath = context.Server.MapPath("upload/thumb_" + fileName);

//保存缩略图

thumbImg.Save(thumbPath);

}

}

}

}

context.Response.Write(strName+",保存成功:");

}

//////////////在图片上添加水印

string phyPath = context.Server.MapPath("upload/1.jpg");

//水印图片路径

string waterImgPath = context.Server.MapPath("images/waterimg.jpg");

//读取物理路径上的图片

using (Image img = Bitmap.FromFile(phyPath))

{

//获得水印图片

using (Image imgWater = Bitmap.FromFile(waterImgPath))

{

//准备好画家对象

using (Graphics g = Graphics.FromImage(img))

{

//g.DrawString("传智播客", new Font("微软雅黑", 12), Brushes.White, 0, 0);

g.DrawImage(imgWater, 0, 0);

img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);

}

}

}

//////////////自己画图 验证码

using (Bitmap img = new Bitmap(120, 30))

{

//创建 画家 对象

using (Graphics g = Graphics.FromImage(img))

{

//填充一个矩形

//g.FillRectangle(Brushes.White, 1, 1, img.Width-2, img.Height-2);

g.FillRectangle(Brushes.White, 0, 0, img.Width, img.Height);

//画上一个 矩形 边框

g.DrawRectangle(Pens.Red, 0, 0, img.Width-2, img.Height-2);

//作画

g.DrawString(strVcode, new Font("微软雅黑", 12), Brushes.Black, 0, 0);

img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);

}

}

/////////////////////////////////////////////////////下载文件

string fileName=context.Request.QueryString["fname"];

string phyFile = context.Server.MapPath("images/" + fileName);

//向响应报文头中 追加一项,告诉浏览器请使用 另存为 的方式 提示用户保存该文件

context.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);

context.Response.WriteFile(phyFile);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: