DLL內嵌圖片資源

來源:互聯網
上載者:User
文章目錄
  •     載入圖片資源
  •    資源路徑:
  •     顯示所有內嵌資源

如果你在net程式中使用圖片,你會發現把圖片嵌入到資源檔要比把它作為單獨的檔案,在程式運行時從磁碟裡讀取要方便的多!

      首先,添加圖片資源:

    把圖片作為一個嵌入式資源添加到你的項目中:         
    1.在 Visual Studio, 單擊 Project
菜單, 然後選擇Add Existing Item
. 找到並選擇你想添加到項目中的圖片.
    2.在 Solution Explorer 中, 右擊這個你剛添加到項目中的圖片,如何從彈出的菜單中選擇  Properties
,會出現屬性工具列.
    3.在這個工具列中(如), 改變 Build Action
屬性為 Embedded Resource
.
    4.重建項目,這個圖片將被編譯到你項目的程式集中
   

    載入圖片資源

    確保在你的項目中添加一下引用:

    using
 System.IO;
    using
 System.Reflection;


    為了在程式中載入這個圖片資源,請使用一下代碼:

1
 Assembly myAssembly 
=
 Assembly.GetExecutingAssembly();

2
 Stream myStream 
=
 myAssembly.GetManifestResourceStream( 
"
MyNamespace.SubFolder.MyImage.bmp
"
 );

3
 Bitmap bmp 
=
 
new
 Bitmap( myStream );   資源路徑:

    下面是正確的路徑格式:

    <namespace>.<subfolders>.<image name>.<extension>(
<命名空間>.<檔案夾>.<圖片名>.<尾碼>
)

    說明
:

    namespace
是項目的命名空間.

    extension
是這個圖片的格式(如, "bmp" or "jpg").
    提示: 不像
Windows 檔案路徑, 嵌入式資源路徑是按絕對路徑.

    舉例(如), 這個 About24.png 圖片檔案被儲存在主程式 Art/A 檔案夾下. 這個情況下, 這個路徑將是 "MyNamespace.Art.A.About24.png".

   

    顯示所有內嵌資源

    如果你在確定正確的路徑有麻煩的話,你能使用下面的代碼顯示這個路徑下的所有內嵌資源:

 

1
 Assembly myAssembly 
=
 Assembly.GetExecutingAssembly();

2
 string
[] names 
=
 myAssembly.GetManifestResourceNames();

3
 foreach
 (
string
 name 
in
 names)

4
 {

5
     Console.WriteLine( name );

6
 }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.