您的位置:首页 > 其它

分享一个用于替换复制网页当中的图片地址并保存在服务器的上方法

2013-05-23 14:53 585 查看
/// <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;
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐