views:

188

answers:

5

I have 30 PNGs in a resource file and I would like to iterate around them inside a timer. This timer sets the form's background image to the next PNG in the sequence to produce a basic animation.

I can't find an easy way to enumerate the resource file and get at the actual images. I am also keen to keep the references to the images not fixed to their filenames so that updating the naming of the images within the Resource File would not require me to update this section of code.

Notes:

  • The images inside the resource file are named in sequence ('image001.png', 'image002.png', ...).
  • This resource file is used exclusively to store these images.
A: 

How about this forum answer that uses GetManifestResourceStream() ?

Thorsten79
Thank you for the information, with this approach I need to specify the exact name of the file, is there anyway to avoid that?
CuriousCoder
+1  A: 
    private void Form1_Load(object sender, EventArgs e)
    {
        var list = WindowsFormsApplication1.Properties.Resources.ResourceManager.GetResourceSet(new System.Globalization.CultureInfo("en-us"), true, true);
        foreach (System.Collections.DictionaryEntry img in list)
        {
            System.Diagnostics.Debug.WriteLine(img.Key);
            //use img.Value to get the bitmap
        }

    }
Fredou
I understand this usage of resource files. My question is about how I would then extend this type of usage to say 'given the current image, move to the next image'? Could you provide a code example?
CuriousCoder
+1  A: 
Assembly asm = Assembly.GetExecutingAssembly();
for(int i = 1; i <= 30; i++)
{
  Stream file = asm.GetManifestResourceStream("NameSpace.Resources.Image"+i.ToString("000")+".png");
  // Do something or store the stream
}

To Get the name of all embedded resources:

string[] resourceNames = Assembly.GetManifestResourceNames();
foreach(string resourceName in resourceNames)
{
    System.Console.WriteLine(resourceName);
}

Also, check out the example in the Form1_Load function.

SwDevMan81
The only issue with this method (which will work) would be that if I rename the images (relatively likely to happen in this project) I have to come back and update the code. Do you feel that that is unavoidable?
CuriousCoder
You can get the list of embedded resources, but if you are looking for specific files, I don't see a way around this. If you know that the ONLY files in the resources are your images, you can just use GetManifestResourceNames()
SwDevMan81
Thank you, a combination of GetManifestResourceNames and GetManifestResourceStream will get me very close to the end solution.
CuriousCoder
A: 

Check this blog out: Social MSDN

rfonn
A: 

Here is a nice tutorial on how to extract embedded resources here on CodeProject, and here is how to use an image as alpha-blended, and shows how to load it into an image list. Here's a helper class to make loading embedded resources easier here.

Hope this helps, Best regards, Tom.

tommieb75