More Efficient way to change image in PictureBox - c#

INTRO:
Good day dear coders! I took a look around and wasn't quite able to find answer to my simple question, tho some questions do answer my question, however they seem to be advanced for me to fathom so I'm printing here my simple situation.
QUESTION:
I want to change BackgroundImage or Image of PictureBox and thats how I am doing this:
PictureBox.Image = new Bitmap(#"C:\Users\Ailayna\documents\visual studio 2012\Projects\FormCritterTalking\FormCritterTalking\Character Pictures\CharacterNormal.png");
This picture located in one of my project folders and some how writing whole path to the picture makes no logical sense to me, since I have included all needed pictures to the project, in specific project's folder and I wonder is there a more efficient way of changing picture rather than specifying the whole path of where picture is located?
Is there a way to directly access my folder where my project pictures located using code, like for example: PictureBox.Image = FolderName.PictureName;
I would like to know how are you guys doing this in more efficient and neat way? And another thing is, do I always have to say "new Bitmap"? Can it be something else?

Is there a way to directly access my folder where my project pictures
located using code, like for example: PictureBox.Image =
FolderName.PictureName;
Yes, there is. It's called resources.
In your project select properties then chose resources. Add image.
Access it:
yourProjectName.Properties.Resources.imageName
However I'd recommend to use streams to access images. This is the right way, especially in case of bitmaps. Do not forget to dispose it afterwards. See my answer here how to do this.

I am not aware of any PictureBox control in WPF but if you are looking for the same in WPF You can do it like this in XAML:
<Image Source="/MyProject.UI.Common;component/Images/Cut.png"/>
Here your Image is located inside "Images" folder.

Disclaimer: Since you're loading a picture directly off the hard drive (and I'm assuming it's working) I'm guessing we're talking about a WinForms project.
There are a number of options you can choose from.
The simplest of which is probably getting the current application assembly folder and using that:
How do I get the path of the assembly the code is in?
var dir = AppDomain.CurrentDomain.BaseDirectory;
The images should be copied along with the executable. Then you can either use the code above to get the current directory OR you can try and rely on a relative path (from where the executable is located to the images).
Another option is to add the pictures as resources - these will be part of your application, but the procedure of reading them is a bit more complex.

Related

Refrain from using local path for image in C#

I am loading an image in my program with this code:
Image img = new Bitmap(#"C:\Users\******\Desktop\*****\bin\Debug\image.png");
I would like to keep the location static so I don't have to manually edit the path when I run the program on a different PC.
I am experimenting with the apps.config file as I have heard this is where my solution will lie.
Any help with this would be appreciated!
Why not use Environment.SpecialFolder?
This isn't static, obviously, but you wouldn't have to edit anything. You would really only have to create the folders on the desktop if they don't already exist.
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
Or use System.Environment.CurrentDirectory since it looks like that's where you're putting it anyway...
Image img = new Bitmap(Environment.CurrentDirectory + #"\image.png");
A better solution would be to embed it in a resx file as part of your assembly. That way you wouldn't have to worry about the file being located any differently.
The static property
AppDomain.CurrentDomain.BaseDirectory
points to the path from where the application was started, even if the current directory points somewhere else. You can use this to locate files that are in the same directory as the executable. However, for small images (i.e. GUI components), embedding them as resources is the way to go.

Change pictureBox.Image with c# = FileNotFoundException

i have a small app in C# winform. It work great but i don't understand how to change the image of a picture box in code :
i have this directory for my image :
myProjectDirectory/bin/Pics/myImage.jpg
and this code give me an FileNotFoundException :
this.imgInvader.Image = Image.FromFile("../Pics/invader2.jpg");
i don't understand because i see on stackoverflow that FromFile method begin at bin/Release. So a ../Pics/myImage.jpg should work no ?
Thx
Use the relative path of the image.
this.imgInvader.Image = Image.FromFile(#"bin\Pics\invader2.jpg");
Here give the path from the location where your code behind file is located. Suppose if your file is in root directory and if your images are in bin/Pics/ folder then the above code works. It automatically gets the path related to the location the program is running from.
Trying to reference image files that are outside the executable output directory is incredibly fragile. There are lots of ways it can go wrong (unfortunately, there's not enough context in your question for anyone to know exactly which of these ways is your specific problem).
If you must use files on disk to store your image resources, then they should be copied into the build output directory (i.e. "Release") and referenced there. Add the file to your Visual Studio project, select it, and in the properties window, set the "Build Action" value to "Content". If the file is in a folder under the project, then it will also be copied to a folder of the same name in the output directory.
If you do use files on disk, the other thing to make sure you do is find the executable's directory (e.g. via Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)) and then combine that with your expected relative path (e.g. just the file name, or the file name under whatever folder/subdirectory you gave it in the project, if you did) using the Path.Combine() method, and then using that absolute file name as the source. Otherwise, your code can be confused by changes in the current directory made elsewhere in your program (basically, don't ever rely on the current directory…global state like that is too easy to get mixed up, once you get into the habit of using it).
For example:
string exeDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
string imageFileName = Path.Combine(exeDirectory, "invader2.jpg");
Now, all that said, IMHO it is probably a better idea to add your images as resources in the executable itself, and then reference them from the Properties.Resources class. Then the images are always with the executable, because they are in the same file. The code is a lot easier too, because you're just referencing properties in the Resources class that return the actual Image objects you need.
As the previous comment stated, using resources outside of your exe is not advised however you can still do this by using the Path.GetDirectoryName Method.
I am left to question why your resources are based outside of your exe, why not embed it into your resources located in properties > resources.resx and simply call it with imgInvader.Image = Properties.Resources.FileNamehere; it is a lot safer than trusting the external environment.

including a resource instead of its location

<Application.Resources>
<BitmapImage x:Key="MyImageSource" UriSource="C:\Users\nwrobinson\Pictures\skyskanlogo.jpg" />
</Application.Resources>
hello,
im having an issue with the way C# handles resources, i understand that the above code is a reference to a picture, but i assumed that when the program compiled, it would include the picture for when it runs on other computers. instead, it just crashes when the resource is not present in that location. this makes no sense to me, there has to be a way to include the picture in the program so it will run right?
the way it was explained to me, the application always has to have a photo to reference, so does that mean every time i give someone the application i have to send them the photo as well, or is there a way to have the photo wrapped into the application.
this is my first WPF so im not 100% sure what going on all the time, it might have just been something that was overlooked.
thanks for the help
What you want to do is to add the picture to your project and set its Build Action to Resource. Then you can change your UriSource to something like
UriSource="pack://application:,,,/YourProjectAssembly;component/DirectoryName/FolderName/ImageName"
When you look at the properties for the image in Visual Studio, you can select a Build Action. This can be one of many options, including copying the image to the build folder, embedding it as a resource, and others.
Depending on how you include the image in your project, you will need to use the Pack URI syntax to specify where the image can be found. It is not straightforward, but there are enough examples here (http://msdn.microsoft.com/en-us/library/aa970069(v=vs.110).aspx) for when the resources are embedded etc. that you should be able figure it out. It typically involves specifying the assembly in which the resource is located and a relative path, with a very specific assortment of punctuation interspersed.

Project looking in wrong directory for files(streams)

I've been building a game for the past couple of days. After i've reached certain milestones i'll C&P the project folder into my dropbox folder then create a new one in my visual studio folder.
I've run across a problem now however where when i'm trying to read from files the streamreader is trying to read from the previous folders directory.
SO for example in 'Project2' the reader is trying to read from a file in 'Project1'. How can I change this?
First, you're most likely specifying an absolute directory ( "C:\Blah\BlahBlahblah..." ) or you've set the Working Directory to the wrong place.
Use relative paths or always store your data in a fixed place (the convention these days is to store your data is APPDATA. Storing it in a place like Program Files is a HORRIBLE CONVENTION. Don't do it when you release your program for realsies). Having tagged this with XNA, your root directory should also be specified to a relative place ("Content", "Data", etc.) so that when the executable boots up, it'll look in where the executable is, + inside the folder "Content" or "Data". That will make using the Content Loader easier.
Now, a general recommendation. You should never have to create a new project entirely to do version control. You're literally doing the work of any good free Version Control System (or like this one). Version control will make this much less painful for you.
Finally, a last tip for SO: describing your problem is cool, but what's even better than all of that is combined is posting the code that throws an error. Doing this allows us to figure out what exactly what wrong, because the skilled professionals of SO (of which I am trying to become one) have dealt with and know how to handle many kinds of exceptions and compilation errors (that, or our Google-Fu is stronk).

Visual C# form backgroundImage

I have used a JPG for backgroundImage for an application form.
My question is that do I always need the JPG with the exe program?
So if I give my exe program to another user, the person won't be able to view the backgroundImage if I dont provide the JPG file?
another question is regarding the icons that I use for the program (exe icon and an icon that displays at top of your program).. are these icons stored in the program? or i need to provide the icon file(s)?
sorry i only have a machine and don't have someone to test for me.
cheers,
D
You need to add image as a resource for the Application. If you add it simply as a file link e.g. C:\somelocation as soon as that changes you loose teh image.
If its added as a resource then it is inculded with the build and always present for the Application.
To know more on how to do this look here:
http://msdn.microsoft.com/en-us/library/7k989cfy%28v=vs.80%29.aspx
http://www.homeandlearn.co.uk/csharp/csharp_s4p8.html
An easy test would be to put the .exe in a separate folder and try to launch it.
For the JPG it depends how you refer to it in your program, if it is a resource that you added it will be in the executable.
The icon should be in the executable already.
You can add the .jpg file as a resource in your application, which results in it being compiled into the .exe itself, giving you one less file to distribute.
Check out Accessing an image in the projects resources?

Categories

Resources