[转帖]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 编辑过 |
关键字查询
相关文章
正在查询... |