我們正在研究從我們的服務器下載圖像的C#應用程序。 由於我們正在爲jpeg圖像正常工作,但帶有透明度的png圖像添加了白色補丁以代替透明部分。我嘗試了下面的代碼:如何保持使用c#從url下載的png圖像的透明度#
public Image DownloadImage(string _URL)
{
Image _tmpImage = null;
try
{
// Open a connection
System.Net.HttpWebRequest _HttpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(_URL);
_HttpWebRequest.AllowWriteStreamBuffering = true;
// You can also specify additional header values like the user agent or the referer: (Optional)
_HttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";
_HttpWebRequest.Referer = "http://www.google.com/";
// set timeout for 20 seconds (Optional)
_HttpWebRequest.Timeout = 40000;
_HttpWebRequest.Accept = "image/png,image/*";
// Request response:
System.Net.WebResponse _WebResponse = _HttpWebRequest.GetResponse();
// Open data stream:
System.IO.Stream _WebStream = _WebResponse.GetResponseStream();
// convert webstream to image
_tmpImage = Image.FromStream(_WebStream);
// Cleanup
_WebResponse.Close();
_WebResponse.Close();
}
catch (Exception _Exception)
{
// Error
Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
return null;
}
return _tmpImage;
}
當我們從URL下載它時得到的圖像帶有白色補丁。我猜想它增加了白色補丁來代替透明部分,但我怎麼能阻止它這樣做。有沒有什麼方法可以直接檢測並以適當的格式下載圖像,而無需播放圖像。
我試過這個_HttpWebRequest.Accept =「image/png,image/*」;所以它應該接受PNG圖像和保持寬高比,但它似乎並沒有爲我工作。
任何幫助深表謝意。
感謝你, Santosh Upadhayay。
當您在Windows中查看文件或將圖像分配到「PictureBox」時,是否顯示白色補丁? –
另外,嘗試在你正在寫流的Image對象中設置'PixelFormat',嘗試其中的一些,你需要一個讓Alpha可用的對象。 –
對於先生科林,也在文件瀏覽器和我在那裏追加的地方也。它的下載只有白色補丁 –