img 图片文件操作c#
using System; using System.Drawing; using System.Drawing.Imaging; using System.Drawing.Drawing2D; using System.Web.UI.HtmlControls; namespace HuoLi.Common { /// <summary> /// img 的摘要说明。 /// </summary> public class img { public img() { // // TODO: 在此处添加构造函数逻辑 // } /// <summary> /// 图片处理函数(生成小图) /// </summary> /// <param name="pic_path">原始图片路径</param> /// <param name="pic_path0">要生成的小图片的路径</param> /// <param name="width"></param> /// <param name="height"></param> public static void pic_0(string pic_path,string pic_path0,int width,int height) { System.Drawing.Image img= System.Drawing.Image.FromFile(pic_path); int c_width=width; int c_height=height; int width1=img.Width; int height1=img.Height; int min=(c_width>=c_height?c_height:c_width); if(width1==height1) { c_width=c_height=min; } else { if(width1>height1) { c_height=c_width*height1/width1; if(c_height>height) { c_height=height; c_width=c_height*width1/height1; } } else { c_width=c_height*width1/height1; if(c_width>width) { c_width=width; c_height=c_width*height1/width1; } } } Bitmap bm=new Bitmap(c_width,c_height); Graphics g; g = Graphics.FromImage (bm) ; g.Clear(Color.White); //对选中的原始图片区域进行拖放,拖放到width,height大小 Rectangle rec=new Rectangle(0,0,c_width,c_height); //选中原始图片的区域,[0,0,width1,height1]为选中块的坐标,可以画图软件看到效果 g.DrawImage(img,rec,0,0,width1,height1,GraphicsUnit.Pixel ); bm.Save(pic_path0, ImageFormat.Jpeg); img.Dispose(); g.Dispose(); bm.Dispose(); } /// <summary> /// 上传文件并生成小图片,删除原始图片 /// </summary> /// <param name="File1"></param> /// <param name="SaveFileFolder">保存文件夹的路径,如: "UpFiles/"</param> /// <returns>小图片的相对存放路径 string</returns> public static string SaveSmallImages(HtmlInputFile File1,string SaveFileFolder) { string p = string.Empty; //首页图片定义 if (File1.Value!="") { string fv = File1.Value; string ext = System.IO.Path.GetExtension(fv); string newNameB = Guid.NewGuid().ToString("n"); string oldNameAll = newNameB+ext; string newNameAll = "s"+newNameB+ext; string smOldPath = System.Web.HttpContext.Current.Server.MapPath(SaveFileFolder)+oldNameAll; string smNewPath = System.Web.HttpContext.Current.Server.MapPath(SaveFileFolder)+newNameAll; string smSaveNewPath = SaveFileFolder + newNameAll; if (System.IO.File.Exists(smOldPath)) { Location.MsgBox("已存在相同文件名,请重新上传JPG图片!"); } else { ReadXML rdxml = new ReadXML(); string smFolder = System.Web.HttpContext.Current.Server.MapPath("UpFiles/"); if (!System.IO.Directory.Exists(smFolder)) { System.IO.Directory.CreateDirectory(smFolder); } File1.PostedFile.SaveAs(smOldPath); pic_0(smOldPath,smNewPath,rdxml.smallPicWidth,rdxml.smallPicHeight); //生成首页小图片; p = smSaveNewPath; if (System.IO.File.Exists(smOldPath)) { System.IO.File.Delete(smOldPath); } } } return p; } } }