33

我想像这样加载图像:

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;
    }
}

这样的事情可能吗?

4

6 回答 6

53

您始终可以使用which 返回此类使用System.Resources.ResourceManager的缓存。ResourceManager由于chan1chan2代表两个不同的图像,您可以使用System.Resources.ResourceManager.GetObject(string name)which 返回与您的输入匹配的对象与项目资源

例子

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

谢谢,
我希望你觉得这有帮助:)

于 2012-11-27T20:17:49.523 回答
11

您可以使用以下方法执行此操作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;
}
于 2012-11-27T20:17:07.400 回答
7

试试这个WPF

StreamResourceInfo sri = Application.GetResourceStream(new Uri("pack://application:,,,/WpfGifImage001;Component/Images/Progess_Green.gif"));
picBox1.Image = System.Drawing.Image.FromStream(sri.Stream);
于 2014-05-30T11:30:28.440 回答
4

如果您的图像在资源文件中,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;
    }
于 2012-11-27T20:31:11.587 回答
0
    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);
于 2014-12-16T09:52:07.983 回答
-2

您可以在项目中添加图像资源,然后(右键单击项目并选择“属性”项)以这种方式访问​​它:

this.picturebox.image = projectname.properties.resources.imagename;
于 2014-12-09T18:53:17.973 回答