Nabou
Nabou

Reputation: 549

PNG and jpg images not appearing in C# application

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);

Upvotes: 0

Views: 4790

Answers (2)

JMarsch
JMarsch

Reputation: 21753

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

  1. Path that was actually being used was different from the path you needed.
  2. The path was correct, but your files weren't there (build/copy/install problem)
  3. 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.

Upvotes: 0

KV Prajapati
KV Prajapati

Reputation: 94645

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.

Upvotes: 2

Related Questions