从资源加载图像
我想加载这样的图像:
void info(string channel) { //Something like that channelPic.Image = Properties.Resources.+channel }
因为我不想这样做
void info(string channel) { switch(channel) { case "chan1": channelPic.Image = Properties.Resources.chan1; break; case "chan2": channelPic.Image = Properties.Resources.chan2; break; } }
这样的事情可能吗?
您始终可以使用System.Resources.ResourceManager
,它返回此类使用的缓存ResourceManager
。 由于chan1
和chan2
代表两个不同的图像,您可以使用System.Resources.ResourceManager.GetObject(string name)
,它返回与您的输入匹配的对象与项目资源
例
object O = Resources.ResourceManager.GetObject("chan1"); //Return an object from the image chan1.png in the project channelPic.Image = (Image)O; //Set the Image property of channelPic to the returned object as Image
注意 :如果在项目资源中找不到指定的字符串,则Resources.ResourceManager.GetObject(string name)
可能返回null
。
谢谢,
我希望你觉得这有用 :)
您可以使用ResourceManager
执行此操作:
public bool info(string channel) { object o = Properties.Resources.ResourceManager.GetObject(channel); if (o is Image) { channelPic.Image = o as Image; return true; } return false; }
试试这个WPF吧
StreamResourceInfo sri = Application.GetResourceStream(new Uri("pack://application:,,,/WpfGifImage001;Component/Images/Progess_Green.gif")); picBox1.Image = System.Drawing.Image.FromStream(sri.Stream);
如果您的图像位于资源文件中,ResourceManager将起作用。 如果它只是项目中的一个文件(让我们说根),你可以使用这样的东西得到它:
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly(); System.IO.Stream file = assembly .GetManifestResourceStream("AssemblyName." + channel); this.pictureBox1.Image = Image.FromStream(file);
或者如果你在WPF:
private ImageSource GetImage(string channel) { StreamResourceInfo sri = Application.GetResourceStream(new Uri("/TestApp;component/" + channel, UriKind.Relative)); BitmapImage bmp = new BitmapImage(); bmp.BeginInit(); bmp.StreamSource = sri.Stream; bmp.EndInit(); return bmp; }
this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.toolStrip1.Location = new System.Drawing.Point(0, 0); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(444, 25); this.toolStrip1.TabIndex = 0; this.toolStrip1.Text = "toolStrip1"; object O = global::WindowsFormsApplication1.Properties.Resources.ResourceManager.GetObject("best_robust_ghost"); ToolStripButton btn = new ToolStripButton("m1"); btn.DisplayStyle = ToolStripItemDisplayStyle.Image; btn.Image = (Image)O; this.toolStrip1.Items.Add(btn); this.Controls.Add(this.toolStrip1);
您可以在项目中添加图像资源(右键单击项目并选择“ 属性”项)以这种方式访问:
this.picturebox.image = projectname.properties.resources.imagename;