如何将Image URL转换为ImageStream?

时间:2013-11-29 23:22:05

标签: c# asp.net asp.net-mvc

我这样做是为了本地形象

var imgstream = System.IO.File.OpenRead(@"C:\Users\TheSarfaraz\Downloads\SampleFacebookApp\SampleFacebookApp\SampleFacebookApp\Content\images\dreams-facebook-cover_4173.jpg");

但它不允许我为图片网址

这样做

如果我试试这个

var imgstream = System.IO.File.OpenRead(@"http://www.trendycovers.com/covers/Listen_to_your_heart_facebook_cover_1330517429.jpg?i");

我收到此错误

URI formats are not supported.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.ArgumentException: URI formats are not supported.

2 个答案:

答案 0 :(得分:2)

您不能要求将Web资源(例如图像)视为常规文件并在其上使用I / O操作,例如FileStream

在您的情况下,您应该使用正在使用HTTP GET方法的WebClient类来正确下载图像。

例如:

using (WebClient Client = new WebClient ())
{
    Client.DownloadFile(@"http://www.trendycovers.com/covers/Listen_to_your_heart_facebook_cover_1330517429.jpg?i", "Listen_to_your_heart_facebook_cover_1330517429.jpg");
}

除非您在第二个参数(fileName)中声明绝对路径,否则图像文件将下载到您的应用程序文件夹,例如:c:\images\Listen_to_your_heart_facebook_cover_1330517429.jpg

答案 1 :(得分:1)

您使用的是错误的课程。您无法使用File.OpenRead函数从Web服务器读取文件,因为这不是为此目的而设计的。请尝试使用WebClient.OpenRead函数。