1.调用
注:string Path=“A:\新建文件夹名字\XXX.(jpg\pdf\png\jpeg…)”;都根据不同后缀来获取不同图片格式
//Url地址
string downloadUrl = "[https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1605861582&di=70a4d94865ce618630567f9a79cb6f4f&src=http://ku.90sjimg.com/back_pic/04/81/48/5258c4b0209d3d7.jpg](https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1605861582&di=70a4d94865ce618630567f9a79cb6f4f&src=http://ku.90sjimg.com/back_pic/04/81/48/5258c4b0209d3d7.jpg)"
//Path图片的地址+名字(如果下载的是PDF格式就把JPG改成PDF)
string Path="A:\\新建文件夹名字\\XXX.jpg";
GetUrlTOjpgORpdf(downloadUrl ,Path);
2.方法
#region 把http的pdf地址转换成本地址下的pdf
/// <summary>
/// 把http的pdf地址转换成本地址下的pdf
/// </summary>
/// <param name="url">http的url地址</param>
/// <param name="PathBen">本地生成PDF的文件夹</param>
private void GetUrlTOjpgORpdf(string Url, string PathBen)
{
try
{
//发出对统一资源标识符的请求
System.Net.WebRequest Webrequest = System.Net.WebRequest.Create(Url);
//获取Url返回的类型(请求Get类型)
Webrequest.Method = "GET";
//获得用户名密码的Base64编码 添加Authorization到HTTP头 不需要的账号密码的可以注释下面两行代码
string code = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "userName", "passWord")));
Webrequest.Headers.Add("Authorization", "Basic " + code);
byte[] filebyteArray;
//提供来自统一资源标识符(Url)的响应
using (WebResponse webRes = Webrequest.GetResponse())
{
//获取或设备接收数据内容的长度
int length = (int)webRes.ContentLength;
//WebResponse类的HTTP特定实现
HttpWebResponse response = webRes as HttpWebResponse;
//获取流,改流用于读取来自服务器的的响应体
Stream stream = response.GetResponseStream();
//读取到内存
MemoryStream Memorystream = new MemoryStream();
//把获取的内容转换成byte类型
byte[] buffer = new byte[length];
int i;
//将字节逐个放入到Byte中
while ((i = stream.Read(buffer, 0, buffer.Length)) > 0)
{
Memorystream.Write(buffer, 0, i);
}
//将流内容写入字节数组
filebyteArray = Memorystream.ToArray();//文件流Byte,需要文件流可直接return,不需要下面的保存代码
Memorystream.Close();
//基于指定的字节数组初始化MemoryStream类的无法调整大小的新实力
MemoryStream MS = new MemoryStream(filebyteArray);
//可根据文件类型自定义后缀
//string file = string.Format("A:\\666666666.pdf");
//string file = string.Format("A:\\666666666.jpg");
string file = string.Format(PathBen);
//使用指定的路径和创建模式初始化FileStream类的新实例
FileStream FS = new FileStream(file, FileMode.OpenOrCreate);
MS.WriteTo(FS);
MS.Close();
FS.Close();
}
}
catch (System.Exception ex)
{
throw ex;
}
}
#endregion