#region======================图片相关操作========================
///
/// 上传图片
///
private void UploadFile()
{
string fileContentType =fileUpload.PostedFile.ContentType; //上传的文件类型
if (fileContentType == "image/bmp" || fileContentType =="image/gif" || fileContentType == "image/pjpeg" || fileContentType== "image/jpg" || fileContentType == "image/x-png")
{
FileInfo file = new FileInfo(Server.MapPath("../UploadFile/" +labPic.Text));
if (file.Exists)
file.Delete(); //删除原来的图片
string name =fileUpload.PostedFile.FileName; // 客户端文件路径
file = new FileInfo(name);
string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") +file.Extension; // 文件名称
labPic.Text = fileName;
string strfilename = "../UploadFile/" +fileName; //文件路径
string webFilePath =Server.MapPath(@strfilename); // 服务器端文件路径
if (File.Exists(webFilePath))
{
ClientScript.RegisterStartupScript(this.GetType(), "1","
return;
}
HttpPostedFile hpf = fileUpload.PostedFile;
hpf.SaveAs(webFilePath); //保存文件
check.ResizeImg(webFilePath);
string fileName1 = DateTime.Now.ToString("yyyyMMddHHmmssmm") + "1"+ file.Extension;
labPic.Text = fileName1;
CreatWaterMarkText(DateTime.Now.ToShortDateString(), strfilename,fileName1);
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "2","
labPic.Text = " ";//防止显示NULL
return;
}
}
///
/// 添加水印
///
/// 要添加的水印文字
/// 源图片路径
/// 存储的文件路径
public void CreatWaterMarkText(string waterText, string sourcePath,string savePath)
{
System.Drawing.Image pic =System.Drawing.Image.FromFile(Server.MapPath(sourcePath));
Graphics g = Graphics.FromImage(pic);
Brush brush = new SolidBrush(Color.Black);//创建一把刷子
g.DrawString(waterText, new Font("宋体", 18), brush, 1,1);//给图片(pic)加水印
pic.Save(Server.MapPath(string.Format("../UploadFile/{0}",savePath)), System.Drawing.Imaging.ImageFormat.Jpeg);
g.Dispose();
}
///
/// 按照指定大小压缩图片并保存
///
/// 图片所在文件夹
/// 指定的图片宽度
/// 指定的图片高度
public void ResizeImg(string ImgFile, int maxWidth, intmaxHeight)
{
System.Drawing.Image imgPhoto =System.Drawing.Image.FromFile(ImgFile);
//新建一个bmp图片
System.Drawing.Image bitmap = new System.Drawing.Bitmap(maxWidth,maxHeight);
//新建一个画板
System.Drawing.Graphics g =System.Drawing.Graphics.FromImage(bitmap);
//设置高质量插值法
g.InterpolationMode =System.Drawing.Drawing2D.InterpolationMode.High;
//设置高质量,低速度呈现平滑程度
g.SmoothingMode =System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//清空画布并以透明背景色填充
g.Clear(System.Drawing.Color.Transparent);
//在指定位置并且按指定大小绘制原图片的指定部分
g.DrawImage(imgPhoto, 0, 0, maxWidth, maxHeight);
g.Dispose();
imgPhoto.Dispose();
imgPhoto = (System.Drawing.Image)bitmap.Clone();
imgPhoto.Save(ImgFile,System.Drawing.Imaging.ImageFormat.Jpeg);
bitmap.Dispose();
}
#endregion