How to programatically access images in a resource file? - c#

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.

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

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.

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.

How about this forum answer that uses GetManifestResourceStream() ?

Related

Combining a string and resource

I have a dataset which contains some products and their image filenames (for example "test.png").
Images are loaded as resources. How can I set the image location properly?
DataRowView uRow = (DataRowView)comboBox1.SelectedItem;
DataRow row = uRow.Row;
pictureBox1.ImageLocation = Properties.Resources + row["logo"].ToString();
You can get a string resource by name like this:
string imageName = row["logo"].ToString();
// Strip off the extension, since it is not contained in the resource name.
imageName = Path.GetFileNameWithoutExtension(imageName);
pictureBox1.ImageLocation =
Properties.Resources.ResourceManager.GetString(imageName);
If you have stored the images themselves as resources, you can get them by name like this:
pictureBox1.Image =
(Image)Properties.Resources.ResourceManager.GetObject(imageName);
The ImageLocation property does not support using resources directly. From the MSDN Docs:
Gets or sets the path or URL for the image to display in the
PictureBox.
To load an image that is a resource, please see Change PictureBox's image to image from my resources?
If you set property Access modifier of Resources.resx file to the Friend or Public
then images or another resources can be accessed without hardcoding names.
Visual Studio will generate a class and properties for every resources
pictureBox1.Image = Properties.Resources.YourImage;

Playing wav file, concatenating string to call file

I am (after some strangeness with my resources file) able to play a .wav file in my project:
SoundPlayer player = new SoundPlayer();
player.Stream = Sounds.L1;
Player.Play();
This works fine but what I want to do is be able to concatenate a string together and then call the file. The .wav filename would be of the form "L" + int, with int being anywhere between 1 - 99 i.e. L1, L2...L99. All the different sound files are in a resx file title Sounds.
How would I be able to call them?
I am trying to use the ResXResourceSet resxSet = new ResXResourceSet("btc.Sounds") ResXResourceSet to load the resources file and then use the .getobject() as suggested. However, how do you specify the location of the embedded resource file? If I use a path as above I get an error as it is looking in my bin/debug folder, which is where the .exe is placed. If I explicityly specify the path I get an access error and one thing I am really curious about is the fact that the 'Sounds.resx' file is an embedded resource so it should 'know' where it is and shouldn't need any path... I have tried pretty much every permutation including using Assembly.GetExecutingAssembly().GetManifestResourceStream("btc_I_Cap.Sounds"), #"....\Sounds" #"....\Resources", #"btc.Sounds" "Sounds.resx" and so on and so far nothing. Can someone please put me out of my misery so that I can go 'oh yeah, that was obvious why didn't I think of that!'
Happy halloween.
Thanks.
Use a ResXResrouceSet to call the sound file Something like this:
using (ResXResourceSet resxSet = new ResXResourceSet(resxFile))
{
for (int i = 1; i <= 99; i ++)
{
SoundPlayer simpleSound = (SoundPlayer)resxSet.GetObject("L" + i.ToString());
simpleSound.Play();
}
}

How can I list every resource files of a directory pack URI? [duplicate]

I have a resource assembly with image files in it that are built using Resource or Content build action. This makes these files accessible using the Uris. However I cannot find the way to enumerate such resources.
If I set the build action to Embedded Resource it becomes possible to enumerate the files with the following code:
string[] resources = Assembly.GetExecutingAssembly().GetManifestResourceNames();
but it in turn makes these files inaccessible using Uris.
The question is - how to enumerate resources that are compiled with either Resource or Content build action?
NOTE: As Thomas Levesque pointed out it is possible to enumerate such resources by leveraging the AssemblyAssociatedContentFileAttribute, but it seems to only work for WPF Application assemblies and not for class library ones. So the question is still open.
You can enumerate the AssemblyAssociatedContentFile attributes defined on the assembly :
var resourceUris = Assembly.GetEntryAssembly()
.GetCustomAttributes(typeof(AssemblyAssociatedContentFileAttribute), true)
.Cast<AssemblyAssociatedContentFileAttribute>()
.Select(attr => new Uri(attr.RelativeContentFilePath));
You can also check this page for a way to enumerate BAML resources.
UPDATE : actually the solution above works only for Content files. The method belows returns all resource names (including BAML resources, images, etc) :
public static string[] GetResourceNames()
{
var asm = Assembly.GetEntryAssembly();
string resName = asm.GetName().Name + ".g.resources";
using (var stream = asm.GetManifestResourceStream(resName))
using (var reader = new System.Resources.ResourceReader(stream))
{
return reader.Cast<DictionaryEntry>().Select(entry => (string)entry.Key).ToArray();
}
}

C# - Loading images into a imagelist and listview

I have gotten a program Im working on to load some pictures and display them within a listview after using a openfiledialog. What I am looking to do now is take this one step further and auto-load the images from a directory 'icons' within the application directory. Im not too sure how to go about it, So Im going to paste my current code here, and work it from there...
private void loadImageLibraryToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog1.Multiselect = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if (openFileDialog1.FileNames != null)
{
for (int i = 0; i < openFileDialog1.FileNames.Length; i++)
{
addImage(openFileDialog1.FileNames[i]);
}
}
else
addImage(openFileDialog1.FileName);
}
}
private void addImage(string imageToLoad)
{
if (imageToLoad != "")
{
imageList1.Images.Add(Image.FromFile(imageToLoad));
listView1.BeginUpdate();
listView1.Items.Add(imageToLoad, baseValue++);
listView1.EndUpdate();
}
}
Edit to Clarify: The code provided shows how to load and show the images in a listview control. What Im looking to do now is upon starting the app, load the images automatically from a folder in the programs directory, and then display them in the listview.
Off the top of my head with no IDE so there may be mistakes! try this
var files = System.IO.Directory.GetFiles(System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath) + "\\icons")
files will be an array of strings containing all the files in the directory which you can then loop as you have above using the array
openFileDialog1.FileNames
The \ may not be required before icons, I can't remember if GetDirectoryName drops the trailing \ from the path or not.
you can also pass a filter to GetFiles to only return certain file types.
HTH
EDIT: I have edited the code above to use
System.Windows.Forms.Application.ExecutablePath
rather than
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase
On testing the code now I have access to an IDE it seems the CodeBase property prepends the path with file:/// which caused my IDE to blow up with an error saying
URI formats are not supported
the code now works in my IDE, You need to make sure your icons Directory is in the same directory as your executable so in my case ....bin\debug\
Give this a try and if it still fails let me know!

How to retrieve Image from Resources folder of the project in C#

i Have some images in resources folder in my project but i want to change the picture box from these resource files of the project
Consider using Properties.Resources.yourImage
Properties.Resources contains everything that you've added as a resource (see your project properties, resources tab)
Other than that, if you embed the images as resource in your project, you can get at them by calling GetManifestResourceStream on the assembly that you've embedded the images in, something like
Stream imgStream =
Assembly.GetExecutingAssembly().GetManifestResourceStream(
"YourNamespace.resources.ImageName.bmp");
pictureBox.Image = new Bitmap(imgStream);
Don't forget to mark the image as an embedded resource! (You'll need to set the build action for the image in its properties window)
If you're finding that you keep getting back null from GetManifestResourceStream, you may be giving the wrong name. (It can be hard to get the names right) Call GetManifestResourceNames on the assembly; that will give you back all the resource names, and you can find the one in the list that you need.
string img = null;
private void btnShow_Click(object sender, EventArgs e)
{
string imgName;
img = textBox1.Text;
imgName = "images/" + img + ".jpg";
if (imgName == null)
{
MessageBox.Show("no photo");
}
else if (imgName != null)
{
this.picBox1.Image = Image.FromFile("images/" + img + ".jpg");
}
}
Below is the Code to Fetch Image From Resources Folder. Normally we keep images in Resources Folder. but Sometime we have image name only with us. in that case you can Access images from Resources Folder using Image Name only.
Below Code will Demonstrate about it.
private System.Resources.ResourceManager RM = new System.Resources.ResourceManager("YourAppliacationNameSpace.Properties.Resources", typeof(Resources).Assembly);
PbResultImage.Image = (Image)RM.GetObject(YourPictureName);
YourAppliacationNameSpace means name of your Application.
YourPictureName means the Picture you Want to access from Resources Folder. but Picture name must be without Extension e.g. (PNG, GIF, JPEG etc)
hope i will be beneficial to some one.
Thank you.
Right click on the project. Go to Resources tab. Select the existing option and add the image.
Now access in the code by
Image = Properties.Resources.ImageName
Worked for me:
(Bitmap) Properties.Resources.ResourceManager.GetObject("ImageName");
this works for your control too, if you need to call your control by a string or concatenated reference.
Just call the control type first (in this case, a picturebox). Assume i=some number and d=some string:
var i = <some number>;
var d = <some string>;
((PictureBox)this.Controls["pictureBox" + i.ToString()]).Image = (Image)Properties.Resources.ResourceManager.GetObject("dice" + d);
Now it's Possible
pictureBox.Image = Properties.Resources.yourImagename;

Categories

Resources