从资源加载图像

时间:2012-11-27 20:05:36

标签: c# image resources picturebox

我想像这样加载图片:

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

这样的事情可能吗?

6 个答案:

答案 0 :(得分:45)

您始终可以使用System.Resources.ResourceManager返回此类使用的缓存ResourceManager。由于chan1chan2代表两个不同的图像,因此您可以使用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

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

答案 1 :(得分:10)

您可以使用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;
}

答案 2 :(得分:6)

尝试使用WPF

StreamResourceInfo sri = Application.GetResourceStream(new Uri("pack://application:,,,/WpfGifImage001;Component/Images/Progess_Green.gif"));
picBox1.Image = System.Drawing.Image.FromStream(sri.Stream);

答案 3 :(得分:2)

如果您的图像位于资源文件中,则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;
    }

答案 4 :(得分: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);

答案 5 :(得分:-2)

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

this.picturebox.image = projectname.properties.resources.imagename;