1

我們正在研究從我們的服務器下載圖像的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。

+0

當您在Windows中查看文件或將圖像分配到「PictureBox」時,是否顯示白色補丁? –

+0

另外,嘗試在你正在寫流的Image對象中設置'PixelFormat',嘗試其中的一些,你需要一個讓Alpha可用的對象。 –

+0

對於先生科林,也在文件瀏覽器和我在那裏追加的地方也。它的下載只有白色補丁 –

回答

1

你對圖像做什麼?如果將它們保存到文件或某些您不想將它們轉換爲Image對象的位置,請從流中讀取原始字節並使用FileStream或File.WriteAllBytes將它們保存到文件中。

0

從C#程序下載圖像或任何其他文件的最簡單方法是使用WebClient類的DownloadFile方法。在下面的代碼中,我們爲本地機器上的圖像創建一個文件名和路徑,然後創建一個WebClient類的實例,然後我們調用DownloadFile方法將URL傳遞給圖像以及文件名和路徑。

string fileName = string.Format("{0}{1}", tempDirectory, @"\strip.png"); 
WebClient myWebClient = new WebClient(); 
myWebClient.DownloadFile(imageUrl, fileName); 
相關問題