[轉(zhuǎn)帖]C#根據(jù)圖片url保存圖片到本地
當(dāng)前位置:點(diǎn)晴教程→知識(shí)管理交流
→『 技術(shù)文檔交流 』
傳入圖片鏈接,將該圖片下載保存到指定位置,注意要做好圖片安全校驗(yàn)。 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> /// 調(diào)用方法 /// </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> /// 將數(shù)據(jù)流轉(zhuǎn)化為圖片保存到本地 /// </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> /// 根據(jù)url將圖片轉(zhuǎn)化為數(shù)據(jù)流 /// </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 編輯過 |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |