How to dynamically change backgroundimage in C#.Net? - c#

Now I'm trying to change dynamically MainForm's backgroundimage.
I wrote that following code segment...
this.BackgroundImage = Image.FromFile("Bar1.png");
this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
Image that I want to change is located in my current project.
But I don't know how to use FromFile Method?

Try something like this:
string path = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase );
string filename="yourfilename";
this.BackgroundImage = Image.FromFile(Path.Combine(path ,filename));
or:
string customPath = "d:\testpath";
string filename="yourfilename";
this.BackgroundImage = Image.FromFile(Path.Combine(customPath ,filename));

You can get application startup path with this code:
Application.StartupPath + "\yourimage"
or you can use
System.Reflection.Assembly.GetExecutingAssembly().Location + "\yourimage";

Please read documentation about FromFile method here.
And if you have image in your resource file, you can access it like this:
this.BackgroundImage = Properties.Resources.yourImageName;

OpenFileDialog dialog = new OpenFileDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
this.BackgroundImage = Image.FromFile(dialog.FileName);
this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
}

make a directory named background where your exe located.
copy background jpg file in that directory
add following in form load event
string path = System.IO.Directory.GetCurrentDirectory() + "\background\";
string filename="back.jpg";
this.BackgroundImage = Image.FromFile(Path.Combine(path, filename));
if you changed background jpg file keeping same file name, the background will be changed.

Related

WPF Image.Source does nothing

I've been trying to set the Image.Source in the code behind to a relative path like this:
IMG_3.Source = new BitmapImage(new Uri("./Sprites/Layout/image1.png", UriKind.Relative));
If I use a non existing path, the program crashes.
But this path exists and works just like that as a .Fill in a Rectangle.
Whats wrong here ?
If the image files are located in a folder structure that is relative to the path of your application's executable assembly, you should load them by Content File Pack URIs like this:
try
{
IMG_3.Source = new BitmapImage(
new Uri("pack://application:,,,/Sprites/Layout/image1.png"));
}
catch
{
IMG_3.Source = fallbackImage;
}
I see nothing wrong here. Try using the full path instead. The .Last() is Linq so if you don't want to use this, just do the same thing with count - 1.
string exe = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName.Split('\\').Last();
IMG_3.Source = new BitmapImage(new Uri(System.Reflection.Assembly.GetExecutingAssembly().Location.Substring(0, System.Reflection.Assembly.GetExecutingAssembly().Location.Length - exe.Length) + "/Sprites/Layout/image1.png"));

Loading a bmp file to a picturebox

I am using a picturebox to display a bmp image when a wav file is playing. My problem is that I cannot access image file when my application is used by other computers.My code is stated below:
string chosen_File = "nowplaying.bmp";
string path = Directory.GetCurrentDirectory();
pictureBox1.Image = Image.FromFile(chosen_File);
Any suggestions?
Package the Image with your program and make the chosen_File refer to the
Application.StartUpPath + "\\your.jpg";

Copy and Rename files in WPF C#

I'm using System.Windows.Forms.OpenFileDialog in my WPF application to select images. When user select an image, I'm displaying file name of selected file in a textbox as below.
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Title = "Select image";
fileDialog.InitialDirectory = "";
fileDialog.Filter = "Image Files (*.gif,*.jpg,*.jpeg,*.bmp,*.png)|*.gif;*.jpg;*.jpeg;*.bmp;*.png";
fileDialog.FilterIndex = 1;
fileDialog.RestoreDirectory = true;
if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
txtImagePath.Text = fileDialog.FileName;
}
I have a button as Save in my application. When user click on this button, I need to rename this file to another name and copy it to another directory in my hard drive.
How can I achieve this?
Using File.Copy and methods in the Path class to extract the relevant part of your file
string newDir = #"D:\temp";
string curFile = Path.GetFileName(txtImagePath.Text);
string newPathToFile = Path.Combine(newDir, curFile);
File.Copy(txtImagePath.Text, newPathToFile);
Now the rename operation on the current dir using File.Move
string curDir = Path.GetDirectoryName(textImagePath.Text);
File.Move(txtImagePath.Text, Path.Combine(curDir, "NewNameForFile.txt"));
This code could be improved introducing some error handling
If you want to copy directly the old file in the new dir using the new name then you could write simply
string newPathToFile = #"D:\temp\NewNameForFile.txt";
File.Copy(txtImagePath.Text, newPathToFile);
and then do the rename on the current dir.
How about using:
System.IO.File.Copy
Alternatively, you can start a batch file, using processInfo
You can use File.Copy. Here are the details: http://msdn.microsoft.com/en-us/library/c6cfw35a.aspx. It takes the source file and copies it to a destination, possibly under a new name.

Retrive image file from folder and display into Image Control

I have save my Image using Below code In a Folder in my source file..
now I have to retrvive the same saved Image on my Form
string filename = Path.GetFileName(fileupload1.PostedFile.FileName);
string strtemp = System.DateTime.Now.ToString("ddMMyyhhmmss_") + filename;
fileupload1.SaveAs(Server.MapPath("Image/" + strtemp));
So how should i give a Path to my Image Control
I have tried something like this to get a path of file and folder but simply i cant fetch the image from it into my image folder
Image2.ImageUrl = (Server.MapPath("Image/" + strtemp));
Use it like this:
Image2.ImageUrl = "~/Image/" + strtemp;
Server.MapPath is used to get the physical path of a resource of your server. You need it for operations like saving files. However your physical path is not valid on the web. You should use the virtual path to specify the url.
You can fetch Image like this.:-
Image2.ImageURL = "~/Image/"+strtemp;
Hope this helps you.
Image2.ImageUrl = "~\\Image\\" + strtemp;
Use the above code.
if(!(DropDownList1.SelectedItem.Text==""))
{
string a = DropDownList1.SelectedItem.Text;
string [] q = a.Split('/');
string qq = q[1];
Image1.Visible = true;
Image1.ImageUrl = "~/Images1/" + qq;
}

Load image from resources area of project in C#

I have an image in my project stored at Resources/myimage.jpg. How can I dynamically load this image into Bitmap object?
Are you using Windows Forms? If you've added the image using the Properties/Resources UI, you get access to the image from generated code, so you can simply do this:
var bmp = new Bitmap(WindowsFormsApplication1.Properties.Resources.myimage);
You can get a reference to the image the following way:
Image myImage = Resources.myImage;
If you want to make a copy of the image, you'll need to do the following:
Bitmap bmp = new Bitmap(Resources.myImage);
Don't forget to dispose of bmp when you're done with it. If you don't know the name of the resource image at compile-time, you can use a resource manager:
ResourceManager rm = Resources.ResourceManager;
Bitmap myImage = (Bitmap)rm.GetObject("myImage");
The benefit of the ResourceManager is that you can use it where Resources.myImage would normally be out of scope, or where you want to dynamically access resources. Additionally, this works for sounds, config files, etc.
You need to load it from resource stream.
Bitmap bmp = new Bitmap(
System.Reflection.Assembly.GetEntryAssembly().
GetManifestResourceStream("MyProject.Resources.myimage.png"));
If you want to know all resource names in your assembly, go with:
string[] all = System.Reflection.Assembly.GetEntryAssembly().
GetManifestResourceNames();
foreach (string one in all) {
MessageBox.Show(one);
}
Way easier than most all of the proposed answers
tslMode.Image = global::ProjectName.Properties.Resources.ImageName;
The best thing is to add them as Image Resources in the Resources settings in the Project. Then you can get the image directly by doing Resources.myimage. This will get the image via a generated C# property.
If you just set the image as Embedded Resource you can get it with:
string name = "Resources.myimage.jpg"
string namespaceName = "MyCompany.MyNamespace";
string resource = namespaceName + "." + name;
Type type = typeof(MyCompany.MyNamespace.MyTypeFromSameAssemblyAsResource);
Bitmap image = new Bitmap(type.Assembly.GetManifestResourceStream(resource));
Where MyTypeFromSameAssemblyAsResource is any type that you have in your assembly.
Code I use in several of my projects...
It assumes that you store images in resource only as bitmaps not icons
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);
}
Use below one. I have tested this with Windows form's Grid view cell.
Object rm = Properties.Resources.ResourceManager.GetObject("Resource_Image");
Bitmap myImage = (Bitmap)rm;
Image image = myImage;
Name of "Resource_Image", you can find from the project.
Under the project's name, you can find Properties. Expand it. There you can see Resources.resx file. Open it. Apply your file name as "Resource_Image".
JDS's answer worked best. C# example loading image:
Include the image as Resource (Project tree->Resources, right click to add the desirable file ImageName.png)
Embedded Resource (Project tree->Resources->ImageName.png, right click select properties)
.png file format (.bmp .jpg should also be OK)
pictureBox1.Image = ProjectName.Properties.Resources.ImageName;
Note the followings:
The resource image file is "ImageName.png", file extension should be omitted.
ProjectName may perhaps be more adequately understood as "Assembly name", which is to be the respective text entry on the Project->Properties page.
The example code line is run successfully using VisualStudio 2015 Community.
I suggest:
System.Reflection.Assembly thisExe;
thisExe = System.Reflection.Assembly.GetExecutingAssembly();
System.IO.Stream file =
thisExe.GetManifestResourceStream("AssemblyName.ImageFile.jpg");
Image yourImage = Image.FromStream(file);
From msdn:
http://msdn.microsoft.com/en-us/library/aa287676(v=vs.71).aspx
Using Image.FromStream is better because you don't need to know the format of the image (bmp, png, ...).
With and ImageBox named "ImagePreview
FormStrings.MyImageNames contains a regular get/set string cast method, which are linked to a scrollbox type list.
The images have the same names as the linked names on the list, except for the .bmp endings.
All bitmaps are dragged into the resources.resx
Object rm = Properties.Resources.ResourceManager.GetObject(FormStrings.MyImageNames);
Bitmap myImage = (Bitmap)rm;
ImagePreview.Image = myImage;
In my case -- I was using Icons in my resource, but I needed to add them dynamically as Images to some ToolStripMenuItem(s). So in the method that I created (which is where the code snippet below comes from), I had to convert the icon resources to bitmaps before I could return them for addition to my MenuItem.
string imageName = myImageNameStr;
imageName = imageName.Replace(" ", "_");
Icon myIcon = (Icon)Resources.ResourceManager.GetObject(imageName);
return myIcon.ToBitmap();
Something else to be aware of, if your image/icon has spaces (" ") in its name when you add them to your resource, VS will automatically replace those spaces with "_"(s). Because, spaces are not a valid character when naming your resource. Which is why I'm using the Replace() method in my referenced code. You can likely just ignore that line.
You can also save the bmp in a var like this:
var bmp = Resources.ImageName;
hope it helps!
Strangely enough, from poking in the designer I find what seems to be a much simpler approach:
The image seems to be available from .Properties.Resources.
I'm simply using an image as all I'm interested in is pasting it into a control with an image on it.
(Net 4.0, VS2010.)
I looked at the designer code from one of my projects and noticed it used this notation
myButton.Image = global::MyProjectName.Properties.Resources.max;
where max is the name of the resource I uploaded into the project.
Or you could use this line when dealing with WPF or Silverlight, especially where you have the source string already in the XAML markup:
(ImageSource)new ImageSourceConverter().ConvertFromString(ImagePath);
Where the ImagePath is something like:
string ImagePath = "/ProjectName;component/Resource/ImageName.png";
This is how I manage to create an ImageList from a Resource (.rc) file of a windows forms application:
ImageList imgList = new ImageList();
var resourceSet = DataBaseIcons.ResourceManager.GetResourceSet(CultureInfo.CreateSpecificCulture("en-EN"), true, true);
foreach (var r in resourceSet)
{
Logger.LogDebug($"Resource Type {((DictionaryEntry)r).Key.ToString()} is of {((DictionaryEntry)r).Value.GetType()}");
if (((DictionaryEntry)r).Value is Bitmap)
{
imgList.Images.Add(((Bitmap)(((DictionaryEntry)r).Value)));
}
else
{
Logger.LogWarning($"Resource Type {((DictionaryEntry)r).Key.ToString()} is of type {((DictionaryEntry)r).Value.GetType()}");
}
}
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);

Categories