我試圖從URL獲取圖片,但是當我將其保存到文件時,它是實際圖片的一半!我搜索了許多網站和解決方案,如HttpWebRequest.BeginGetResponse,因爲我認爲這是因爲我必須緩衝數據,但它不起作用。我不知道這是我的代碼部分是錯誤的,使這個問題:(從URL獲取圖片,但未完全加載
這是從URL獲取圖像的代碼:
public static Bitmap GetImageFromUrl(string url)
{
string RefererUrl = string.Empty;
int TimeoutMs = 22 * 1000;
string requestAccept = "*/*";
string UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7";
Bitmap img = null;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.UserAgent = UserAgent;
request.Timeout = TimeoutMs;
request.ReadWriteTimeout = TimeoutMs * 6;
request.Accept = requestAccept;
if (!string.IsNullOrEmpty(RefererUrl))
{
request.Referer = RefererUrl;
}
try
{
WebResponse wResponse = request.GetResponse();
using (HttpWebResponse response = wResponse as HttpWebResponse)
{
Stream responseStream = response.GetResponseStream();
img = new Bitmap(responseStream);
response.Close();
}
}
catch (Exception)
{
}
return img;
}
這這在文件中保存的圖像的代碼:
byte[] imgBytes = tile.Image;
using (MemoryStream ms = new MemoryStream(imgBytes))
{
using (Image img = Image.FromStream(ms))
{
ms.Dispose();
Bitmap tempBmp = new Bitmap(img);
img.Dispose();
string activeDir = Environment.CurrentDirectory;
string newPath = System.IO.Path.Combine(activeDir, "Images");
System.IO.Directory.CreateDirectory(newPath);
newPath = System.IO.Path.Combine(newPath, tile.TileType.ToString());
System.IO.Directory.CreateDirectory(newPath);
newPath = System.IO.Path.Combine(newPath, tile.Zoom.ToString());
System.IO.Directory.CreateDirectory(newPath);
newPath = System.IO.Path.Combine(newPath, tile.X.ToString());
System.IO.Directory.CreateDirectory(newPath);
newPath = System.IO.Path.Combine(newPath, tile.Y.ToString());
System.IO.Directory.CreateDirectory(newPath);
string newFileName = "tile.png";
newPath = System.IO.Path.Combine(newPath, newFileName);
tempBmp.Save(newPath, ImageFormat.Png);
tempBmp.Dispose();
它工作。非常感謝你。我不知道爲什麼我的代碼無法正常工作。 – Arash 2012-02-27 09:06:14
除了代碼中的某處出現小錯誤,最大的問題是您實際上正在讀取圖像,然後將其保存到文件中。這會導致不必要的圖像處理和保存的其他文件(它看起來相同,但下載的文件將與服務器上的文件不同) – 2012-02-27 09:10:47