C#
[C#] WPF Resource에서 이미지 파일(BitmapImage) 코드로 가져오기
by Jcoder
2021. 12. 7.
빌드 작업 Resource로
public MainWindow()
{
InitializeComponent();
SetImage();
}
private void SetImage()
{
var streamResource = Application.GetResourceStream(LoadBitmapFromResource("/Resources/chromaKey_001.jpg"));
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.StreamSource = streamResource.Stream;
bitmapImage.EndInit();
img_box.Source = bitmapImage;
}
/// <summary>
/// Load a resource WPF-BitmapImage (png, bmp, ...) from embedded resource defined as 'Resource' not as 'Embedded resource'.
/// </summary>
/// <param name="pathInApplication">Path without starting slash</param>
/// <param name="assembly">Usually 'Assembly.GetExecutingAssembly()'. If not mentionned, I will use the calling assembly</param>
/// <returns></returns>
public static Uri LoadBitmapFromResource(string pathInApplication, Assembly assembly = null)
{
if (assembly == null)
{
assembly = Assembly.GetCallingAssembly();
}
if (pathInApplication[0] == '/')
{
pathInApplication = pathInApplication.Substring(1);
}
return new Uri(@"pack://application:,,,/" + assembly.GetName().Name + ";component/" + pathInApplication, UriKind.Absolute);
}