我们如何通过 MVC 和 C# 中的 Uri 从其他网站获取图像 byte[]?
How we can get image byte[] from other website by Uri in MVC and C#?
如果我们有这样的 Uri:
uri = new Uri(info.ImageAddress);
图片地址有这个地址:
http://www.pictofigo.com/assets/uploads/pictures/0/3466/thumb-vacation-pictofigo-hi-005.png
如何在mvc中获取图像数据?
这篇answer to the question How to download image from url using c#应该能帮到你。
您可以使用Image.FromStream
加载任何类型的常用位图(jpg、png、bmp、gif、...),它会自动检测文件类型,您甚至不需要检查url 扩展(这不是一个很好的做法)。例如:
using (WebClient webClient = new WebClient())
{
byte [] data = webClient.DownloadData("https://fbcdn-sphotos-h-a.akamaihd.net/hphotos-ak-xpf1/v/t34.0-12/10555140_10201501435212873_1318258071_n.jpg?oh=97ebc03895b7acee9aebbde7d6b002bf&oe=53C9ABB0&__gda__=1405685729_110e04e71d9");
using (MemoryStream mem = new MemoryStream(data))
{
using (var yourImage = Image.FromStream(mem))
{
// If you want it as Png
yourImage.Save("path_to_your_file.png", ImageFormat.Png) ;
// If you want it as Jpeg
yourImage.Save("path_to_your_file.jpg", ImageFormat.Jpeg) ;
}
}
}
您需要使用类似 HttpClient 调用的方法并将文件流式传输回文件流,然后可用于将文件保存到 http 响应或直接保存到磁盘:
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(HttpMethod.Get, requestUri))
{
using (
Stream contentStream = await(await httpClient.SendAsync(request)).Content.ReadAsStreamAsync(),
stream = new FileStream("MyImage", FileMode.Create, FileAccess.Write, FileShare.None, Constants.LargeBufferSize, true))
{
await contentStream.CopyToAsync(stream);
}
}
}
这当然是一个异步调用,因为它可能是一个大文件。
如果我们有这样的 Uri:
uri = new Uri(info.ImageAddress);
图片地址有这个地址:
http://www.pictofigo.com/assets/uploads/pictures/0/3466/thumb-vacation-pictofigo-hi-005.png
如何在mvc中获取图像数据?
这篇answer to the question How to download image from url using c#应该能帮到你。
您可以使用Image.FromStream
加载任何类型的常用位图(jpg、png、bmp、gif、...),它会自动检测文件类型,您甚至不需要检查url 扩展(这不是一个很好的做法)。例如:
using (WebClient webClient = new WebClient())
{
byte [] data = webClient.DownloadData("https://fbcdn-sphotos-h-a.akamaihd.net/hphotos-ak-xpf1/v/t34.0-12/10555140_10201501435212873_1318258071_n.jpg?oh=97ebc03895b7acee9aebbde7d6b002bf&oe=53C9ABB0&__gda__=1405685729_110e04e71d9");
using (MemoryStream mem = new MemoryStream(data))
{
using (var yourImage = Image.FromStream(mem))
{
// If you want it as Png
yourImage.Save("path_to_your_file.png", ImageFormat.Png) ;
// If you want it as Jpeg
yourImage.Save("path_to_your_file.jpg", ImageFormat.Jpeg) ;
}
}
}
您需要使用类似 HttpClient 调用的方法并将文件流式传输回文件流,然后可用于将文件保存到 http 响应或直接保存到磁盘:
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(HttpMethod.Get, requestUri))
{
using (
Stream contentStream = await(await httpClient.SendAsync(request)).Content.ReadAsStreamAsync(),
stream = new FileStream("MyImage", FileMode.Create, FileAccess.Write, FileShare.None, Constants.LargeBufferSize, true))
{
await contentStream.CopyToAsync(stream);
}
}
}
这当然是一个异步调用,因为它可能是一个大文件。