文章目錄
如果你在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
}