方式一:
/// <summary> /// 从程序集中加载图片 /// </summary> /// <param name="imagePathName">图片路径(该图片必须是嵌入的资源)</param> /// <returns>Bitmap 格式图片</returns> public Bitmap GetIcon(string imagePathName) { Bitmap b = null; try { Assembly asm1 = Assembly.GetExecutingAssembly(); string name = asm1.GetName().Name; asm1.GetManifestResourceStream(imagePathName); Stream imageStream = asm1.GetManifestResourceStream(imagePathName); if (imageStream != null) { b = new Bitmap(Image.FromStream(imageStream)); b.MakeTransparent(); } } catch (Exception e) { throw new Exception(e.Message); } return b; }
小注:
1、imagePathName= Assembly.GetExecutingAssembly().GetName().Name.ToString()+ ".Resources" + ".SelectCate.png";
2、图片要做为项目资源参与编译如下图:
方式二、
/// <summary> /// 根据图片路径加载图片 /// </summary> /// <param name="imagePathName">图片路径</param> /// <returns>Bitmap格式图片</returns> public Bitmap GetToolIcon(string imagePathName) { Bitmap b = null; if (!File.Exists(imagePathName)) { MessageBox.Show("该路径下:" + imagePathName.ToString() + "!文件找不到"); return b; } try { FileStream fs = new FileStream(imagePathName, FileMode.Open, FileAccess.Read); b = (Bitmap)System.Drawing.Bitmap.FromStream(fs); } catch (Exception e) { throw new Exception(e.Message); } return b; }
时间: 2024-10-29 20:48:47