我的项目中有一张图像存储在Resources/myimage.jpg中。我如何动态加载这张图像到位图对象?


当前回答

和ImageBox命名为ImagePreview FormStrings。MyImageNames包含一个常规的get/set字符串强制转换方法,该方法链接到滚动框类型列表。 这些图像的名称与列表中的链接名称相同,除了.bmp结尾。 所有位图都被拖到resources.resx中

Object rm = Properties.Resources.ResourceManager.GetObject(FormStrings.MyImageNames);
Bitmap myImage = (Bitmap)rm;
ImagePreview.Image = myImage;

其他回答

你也可以像这样在var中保存bmp:

var bmp = Resources.ImageName;

希望能有所帮助!

你可以通过以下方式获取图像的引用:

Image myImage = Resources.myImage;

如果你想复制图像,你需要做以下操作:

Bitmap bmp = new Bitmap(Resources.myImage);

用完后别忘了把bmp处理掉。如果你在编译时不知道资源映像的名称,你可以使用资源管理器:

ResourceManager rm = Resources.ResourceManager;
Bitmap myImage = (Bitmap)rm.GetObject("myImage");

ResourceManager的好处是你可以在Resources。myImage通常超出作用域,或者在您想动态访问资源的位置。此外,这适用于声音,配置文件等。

你需要从资源流中加载它。

Bitmap bmp = new Bitmap(
  System.Reflection.Assembly.GetEntryAssembly().
    GetManifestResourceStream("MyProject.Resources.myimage.png"));

如果你想知道程序集中的所有资源名称,请使用:

string[] all = System.Reflection.Assembly.GetEntryAssembly().
  GetManifestResourceNames();

foreach (string one in all) {
    MessageBox.Show(one);
}
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);

我在我的几个项目中使用的代码… 它假设您在资源中存储的图像仅为位图,而不是图标

    public static Bitmap GetImageByName(string imageName)
    {
        System.Reflection.Assembly asm = System.Reflection.Assembly.GetExecutingAssembly();
        string resourceName = asm.GetName().Name + ".Properties.Resources";
        var rm = new System.Resources.ResourceManager(resourceName, asm);
        return (Bitmap)rm.GetObject(imageName);

    }