分享一个用于替换复制网页当中的图片地址并保存在服务器的上方法
/// <summary> /// 替换文章中的图片,并保存下来。 /// </summary> /// <param name="content">内容</param> /// <param name="newImageList">新保存后的图片地址</param> /// <param name="folder">保存的根目录</param> /// <param name="path">保存的绝对地址</param> /// <returns>保存更新了图片地址的文章内容</returns> public static string ReplaceContentImageList(string content, out string[] newImageList, string folder, string path) { string[] imageList = GetHtmlImageUrlList(content); imageList = imageList.Distinct().ToArray();//去除重复的 newImageList = new string[imageList.Length]; int index = 0; if (imageList.Length > 0) { foreach (string img in imageList) { WebClient wc = new WebClient(); Stream stream = wc.OpenRead(img); string imgFormat = img.Substring(img.LastIndexOf(".")); using (Bitmap orginal = new Bitmap(stream)) { //orginal.Save("c://out.jpg", System.Drawing.Imaging.ImageFormat.Jpeg); /*MemoryStream ms = new MemoryStream();*/ /*newimage.Save(ms, ImageFormat.Jpeg); */ //Response.ContentType = "image/Jpeg"; //newimage.Save(Response.OutputStream, ImageFormat.Jpeg); //string folder = "~/Content/" + DateTime.Now.Month.ToString(); //if (Directory.Exists(Server.MapPath(folder)) == false)//如果不存在就创建file文件夹 //{ // Directory.CreateDirectory(Server.MapPath(folder)); //} string fileName = Guid.NewGuid().ToString().Replace("-", "") + imgFormat; string filePath = path + "/" + fileName; string replaceImg = folder.Replace("~", "") + "/" + fileName; switch (imgFormat.ToLower()) { case ".jpg": case ".jpeg": orginal.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg); break; case ".gif": orginal.Save(filePath, System.Drawing.Imaging.ImageFormat.Gif); break; case ".bmp": orginal.Save(filePath, System.Drawing.Imaging.ImageFormat.Bmp); break; case ".png": orginal.Save(filePath, System.Drawing.Imaging.ImageFormat.Png); break; case ".icon": orginal.Save(filePath, System.Drawing.Imaging.ImageFormat.Icon); break; default: break; } newImageList[index++] = replaceImg; content = content.Replace(img, replaceImg); } } } return content; }
作者:Bober Song
出处:http://bober.cnblogs.com/
CARE健康网: http://www.aicareyou.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://bober.cnblogs.com/
CARE健康网: http://www.aicareyou.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。