May 19, 2005

GetBitmapFromResources

Code to get a bitmap resource from the current Assembly
 /// <summary>
 /// Retrieves a bitmap out of the application's resources.
 /// </summary>
 /// <param name="path">Path of the resource</param>
 /// <returns>An image.</returns>
 public static Image GetBitmapFromResources( string path )
 {
  // Assembly containing the resources
  Assembly source = Assembly.GetExecutingAssembly();
 
  // Create and return image
  if ( source.GetManifestResourceStream( path ) != null)
   return new Bitmap( source.GetManifestResourceStream( path ) );
  return null;
 }
Loading animated icons from an Assembly
 private static string PrintIconResouceName =
"Controls.Common.PrintAnimated.gif";
 private static string ArchiveIconResouceName =
"Controls.Common.ArchiveAnimated.gif";

 public static Image AnimatedPrintingImage;
 public static Image AnimatedArchivingImage;

 /// <summary>
 /// // Load the animated icons from the Current Assembly
 /// </summary>
 private static void LoadAnimatedIcons()
 {

  System.IO.Stream imgStream = null;
  // get a reference to the current assembly
  System.Reflection.Assembly ass =
System.Reflection.Assembly.GetExecutingAssembly();
      
  // get a list of resource names from the manifest
  //string [] resNames = ass.GetManifestResourceNames();

  imgStream = ass.GetManifestResourceStream(PrintIconResouceName);
  if(!ReferenceEquals(null, imgStream))
  {                   
   AnimatedPrintingImage  = Image.FromStream(imgStream);
   imgStream.Close();
   imgStream = null;
  }
  else
  {
   System.Diagnostics.Debug.WriteLine("FormsHelpers.LoadAnimatedIcons,
- Could not load the Animated Printing Icon!");
  }

  imgStream = ass.GetManifestResourceStream(ArchiveIconResouceName);
  if(!ReferenceEquals(null, imgStream))
  {                   
   AnimatedArchivingImage  = Image.FromStream(imgStream);
   imgStream.Close();
   imgStream = null;
  }
  else
  {
   System.Diagnostics.Debug.WriteLine("FormsHelpers.LoadAnimatedIcons -
Could not load the Animated Printing Icon!");
  }
 }
This can be easily shortened with something like:
AnimatedPrintingImage = new Bitmap( typeof(someclass) , "print.gif");
OR
AnimatedPrintingImage = new Bitmap( ass.GetManifestResourceStream
(ArchiveIconResouceName));
I think.

No comments: