I have a problem with displaying certain images in my application using C#. I am using the Image class to specify the location and the BitmapImage to specify the source. The UriSource is relative and I just specify the name. It worked for some images, but for others, the image simply does not appear. My image instance is 35x35 big and another is 100x100 big (pixels).
Anyone knows why this might be occurring and how to fix it?
Thanks.
Here's the code I used:
Image removeImage = new Image();
removeImage.HorizontalAlignment = HorizontalAlignment.Left;
removeImage.VerticalAlignment = VerticalAlignment.Top;
removeImage.Margin = new Thickness(490, 10, 0, 0);
removeImage.Width = 35;
removeImage.Height = 35;
BitmapImage source = new BitmapImage();
source.BeginInit();
source.UriSource = new Uri("delete.png", UriKind.RelativeOrAbsolute);
source.EndInit();
removeImage.Source = source;
removeImage.Stretch = Stretch.None;
removeImage.Visibility = Visibility.Visible;
removeImage.MouseDown += new MouseButtonEventHandler(removeImage_MouseDown);
Not sure about the location of image files. If images are in your current project folder then you have to set Copy To Output Directory=Copy Always property of image file from Properties Windows.
The best way that I know of to diagnose a problem like that (assuming a quick peer review of the code gets you nowhere), is to use ProcessMonitor: http://technet.microsoft.com/en-us/sysinternals/bb896645
You can use this tool to monitor all of the file activity on your machine (make sure to use the include/exclude filters to limit the noise).
It's very likely that the reason that the images are not showing up is because your application is looking for them in the wrong place (either they didn't get copied, or the relative path is off).
ProcessMonitor will log every attempt that Windows makes to access your .jpg (whether it fails or succeeds). If you search for your file name in the log, you should find it, probably along with an error message, and the full path that Windows was using to open the file.
The most common results I see are
Path that was actually being used was different from the path you needed.
The path was correct, but your files weren't there (build/copy/install problem)
The path was correct, but your web app did not have permissions to read the file.
In all those cases, ProcessMonitor will show you what happened.
Related
I've noticed that when I add a line of <Window.Background></Window.Background> in the XAML file or in the C# code this.Background = new ImageBrush(new BitmapImage(new uri([...])); if I put in the "Uri" this: new Uri(#"pack://application:,,,/Myapp;component/image.jpg") I get an error when I try to compile it which says: "Could not locate resource "image.jpg" "
But if I change this to new Uri(System.IO.Directory.GetCurrentDirectory()+"\\image.jpg"); it never gives me an error. Why???? What is the difference between both methods? I am very comfortable with Directory but why the compiler doesn't show an error "Locating" the resource with IO.Directory? What's the difference?
The questions may sound too noob, but I don't understand why it gives an error in #"pack://application[...] and not with GetCurrentDirectory()
A pack:// Uri, will search embedded resources for the image. The resources are inside the DLL/EXE, rather than deployed to the same folder. To use an image as a WPF Resource you need to set the Build Action on the image to Resource.
Using the Directory approach simply searches the physical file system for the image.
More info here on WPF Pack Uri's.
I have images that is not located in resources but on the disk. The folder is relative to application. I used:
Overview_Picture.Source = new BitmapImage(new Uri(String.Format("file:///{0}/../MyImages /myim.jpg", Directory.GetCurrentDirectory())));
Overview_Picture.Source = new BitmapImage(uriSource);
But those type of code created many problems and messed up GetCurrentDirectory returns that sometime ok and some times not.
So, MyImages folder is located next to Debug folder, how can I use them images there and not as I done, In some other more right way?
As mentioned oftentimes here on SO, the GetCurrentDirectory method does by definition not always return the directory your assembly resides in, but the current working directory. There is a big difference between the two.
What you need is the current assembly folder (and the parent of that). Also, I'm not sure whether it is wanted that the pictures are one folder above the installation folder (which is basically what you're saying when you say they are one level above the Debug folder - in real life that would be one folder above the folder the application is installed to).
Use the following:
string currentAssemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string currentAssemblyParentPath = Path.GetDirectoryName(currentAssemblyPath);
Overview_Picture.Source = new BitmapImage(new Uri(String.Format("file:///{0}/MyImages/myim.jpg", currentAssemblyParentPath)));
Also, there's a stray space after MyImages, which I removed.
An alternative to constructing an absolute Uri from a relative file path would be to just open a FileStream from the relative path, and assign that to the BitmapImage's StreamSource property. Note however that you also have to set BitmapCacheOption.OnLoad when you want to close the stream right after initializing the BitmapImage.
var bitmap = new BitmapImage();
using (var stream = new FileStream("../MyImages/myim.jpg", FileMode.Open))
{
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = stream;
bitmap.EndInit();
bitmap.Freeze(); // optional
}
Overview_Picture.Source = bitmap;
I am trying to capture the screen and save that image into a folder, everything works fine in my local machine. I've created a setup and installed it on another machine and when i run my application it says that path is incorrect. How can i solve this code below shows how i save image and retrieve it
public void capture_screen()
{
Size s = Screen.PrimaryScreen.Bounds.Size;
Bitmap bmp = new Bitmap(s.Width, s.Height);
Graphics g = Graphics.FromImage(bmp);
g.CopyFromScreen(0, 0, 0, 90, s);
System.IO.Stream stream = new System.IO.MemoryStream();
bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
bmp.Save(#"C:\Users\XXXX\Documents\TESTs\MyImage.jpg");
stream.Position = 0;
pbScreenShots.SizeMode = PictureBoxSizeMode.StretchImage;
img =bmp;
pbScreenShots.Image = bmp;
}
How to change this path to make my setup work in any machine?
Why not just write it to the temp folder:
bmp.Save(Path.GetTempPath());
You can try Special Folders but you might need to ensure you have access to it
myDocsFilePath = Environment.SpecialFolder.MyDocuments
Other than this, you must ensure the computer has a "TESTs" folder in my documents, and that "MyImage" doesn't already exist as you may overwrite a valued image. In short, you are probably better taking al-Khwārizmī's answer (+1!), then prompting the user to choose their own filename and destination, unless you require the picture elsewhere.
Use the Environement.UserName property:
bmp.Save(string.Format(#"C:\Users\{0}\Documents\TESTs\MyImage.jpg", Environment.UserName));
Use Envrinment.GetFolderPath(Environment.SpecialFolder.MyDocuments) to get the user's "my document" folder, use Path.Combine to add a sub folder (you must make sure that folder exists or create it, obviously) or file name.
I am using a custom cursor named hand2.cur in my C#-WPF application. I have added the cursor to a folder named Images which has all the images that I use in my application. However I've realized that I cannot add relative path to use my custom cursor as:
Cursor newCur = new Cursor("Images\\hand2.cur");
window.Cursor = newCur;
So I used this:
string absolute = System.IO.Path.GetFullPath("hand2.cur");
Cursor newCur = new Cursor(absolute);
window.Cursor = newCur;
This tries to find the hand2.cur file in the \bin\Release folder. So I added the file there and I got it working.
But the problem is, if I Publish this application and use it on a different computer, it does not work. Now the problem is with the cursor file path, because if I deploy it after commenting those 3 lines, it works correctly. So what do I do to rectify this problem?
I am using other images from the Image folder in my XAML code and they seem to port fine. But then again my knowledge of WPF is limited so if anyone has any ideas, that would help.
EDIT: I have added my Images folder to the project. I have also set the Build Action of the cursor file hand2.cur to Embedded Resource. However when I use the following two lines, I get an XAMLParseException.
System.Windows.Resources.StreamResourceInfo info = Application.GetResourceStream(new Uri("pack://application:,,,/Slideshow;component/Images/hand2.cur"));
window.Cursor = new System.Windows.Input.Cursor(info.Stream);
The Inner Exception field when I view the details of the error reads: {"Cannot locate resource 'images/hand2.cur'."}
You could make the cursor a resource in your app/assembly and then use GetResourceStream with the pack Uri to the resources location. Pass the Stream of the StreamResourceInfo to the ctor of the Cursor. e.g.
var info = Application.GetResourceStream(new Uri("pack://application:,,,/Images/hand2.cur"));
var cursor = new Cursor(info.Stream);
I've got this working after I added the cursor file hand2.cur to my Resource1.resx resource file. Then I used the following statement in my code:
window.Cursor = new Cursor(new System.IO.MemoryStream(MyNameSpace.Resource1.hand2));
C# - Loading image from file resource in different assembly
I have a PNG image file which is stored in a project called SomeProject and displayed various times using XAML in that same project. In a different assembly, I now wish to access that same image. Previously I was simply specifying a relative path to the actual file which worked fine. However, when I build a release installer, the image files are packed into the SomeProject.DLL.
Is there any easy way I can access the PNG file from another assembly without simply resorting to copying the file locally to the second project? I though it might be possible using 'pack://' but I'm not having much luck.
// SomeOtherProject.SomeClass.cs ...
Image logo = new Image();
BitmapImage logoSource = new BitmapImage();
eChamSource.BeginInit();
// Following line works fine is Visual Studio, but obviously not after installation
// logoSource.UriSource = new Uri(#"..\SomeProject\Resources\Images\logo.png", UriKind.Relative);
logoSource.UriSource = new Uri("pack://application:,,,/SomeProject;component/Resources/Images/logo.png");
logoSource.EndInit();
logo.Width = 100; logo.Height = 100;
logo.Source = logoSource;
Any advice would be good.
If the images you wish to use as Content is in another assembly, you must copy them to the main projects directory.
You can use a Build event to do this:
Right click project that contains images -> Properties -> Buil Events -> edit post build to copy images to main project directory.
Then you have to use it as
pack://application:,,,/ContentFile.xaml
(Or)
If you need it in subfolder
pack://application:,,,/Subfolder/ContentFile.xaml
Have a look at this hfor more information http://msdn.microsoft.com/en-us/library/aa970069.aspx
Try to load your other assembly as followed:
Application.LoadComponent(new Uri(#"AnotherAssembly;;;component\AnotherResourceFilePath/logo.png", UriKind.Relative)));
LoadComponent function returns an object. It is up to you to cast it to the appropriate type.