C#将线上图片下载到本地(保存到本地文件/转换成base64)

1、线上图片下载保存到本地文件夹

 

WebClient client = new WebClient();
byte[] vs = client.DownloadData(url);//url为线上图片路径
string ImgName = Commons.Timestamps(DateTime.Now.ToString(), 0) + ".jpg";//给图片起名,这个随意
string path = System.Web.HttpContext.Current.Server.MapPath("~/TempFile");
DirectoryInfo directory = new DirectoryInfo(path);
if (!directory.Exists)//不存在
{
    directory.Create();
}
path = path + "/" + ImgName;
FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
fs.Write(vs, 0, vs.Length);
fs.Close();

 

2、线上图片转换成base64

 

/// <summary>
/// 图片转换base64(在线)
/// </summary>
/// <param name="imageFile">线上图片地址</param>
/// <returns></returns>
public static String CloudImageFile2Base64(String imageFile) 
{
    try
    {
         WebClient client = new WebClient();
         byte[] vs = client.DownloadData(imageFile);
         string base64String = Convert.ToBase64String(vs);
         return base64String;
     }
     catch (Exception)
     {
         return String.Empty;
     }
}

 

3、本地图片转base64

 

/// <summary>
/// 图片转换Base64(本地)
/// </summary>
/// <param name="imageFile">本地图片路径</param>
/// <returns></returns>
public static String ImageFile2Base64(String imageFile)
{
    try
    {
        Image image = Image.FromFile(imageFile);
        MemoryStream ms = new MemoryStream();
        image.Save(ms, image.RawFormat);
        byte[] byteArray = ms.ToArray();
        ms.Close();
        return Convert.ToBase64String(byteArray);
    }
    catch { return null; }
}

 

posted @ 2024-11-04 13:46  小飛  阅读(39)  评论(0编辑  收藏  举报