[轉帖]C#根據圖片url保存圖片到本地
當前位置:點晴教程→知識管理交流
→『 技術文檔交流 』
傳入圖片鏈接,將該圖片下載保存到指定位置,注意要做好圖片安全校驗。 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { public static class SaveImgByUrl { /// <summary> /// 調用方法 /// </summary> public static void SaveImg() { string imgurl = "https://img0.baidu.com/it/u=2229864841,4232235061&fm=26&fmt=auto";//圖片地址 string imgfile = "D:\\1.png"; WriteBytesToFile(imgfile, GetBytesfromUrl(imgurl)); } /// <summary> /// 將數據流轉化為圖片保存到本地 /// </summary> /// <param name="fileName"></param> /// <param name="content"></param> static public void WriteBytesToFile(string fileName, byte[] content) { FileStream fs = new FileStream(fileName, FileMode.create); BinaryWriter w = new BinaryWriter(fs); try { w.Write(content); } finally { fs.Close(); w.Close(); } } /// <summary> /// 根據url將圖片轉化為數據流 /// </summary> /// <param name="url"></param> /// <returns></returns> static public byte[] GetBytesfromUrl(string url) { byte[] b; HttpWebRequest myReq = (HttpWebRequest)WebRequest.create(url); WebResponse myResp = myReq.GetResponse(); Stream stream = myResp.GetResponseStream(); using (BinaryReader br = new BinaryReader(stream)) { b = br.ReadBytes(500000); br.Close(); } myResp.Close(); return b; } } } -------------------------- https://www.cnblogs.com/work-code/p/15439616.html 該文章在 2023/5/20 8:51:41 編輯過 |
關鍵字查詢
相關文章
正在查詢... |