get absolute file path from image in WPF - wpf

I have something like this in my xaml:
<Grid>
<Image Name="image" Source="../../Images/DefaultImage.png" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"></Image>
</Grid>
How can I get (using my code-behind C# code) the absolute path of the image source?

The method which works for me every time is this simple line
(YourImage.Source as BitmapImage).UriSource
In addition you can work on AbsolutePath or AbsoluteUri of UriSource returned according to your need.

When converted from a Uri string or filename, the ImageConverter creates a BitmapDecoder and extracts its first Frame. Getting the Uri should be possible with:
((BitmapFrame)image.Source).Decoder.ToString()
Note that this will generally return an absolute Uri rather than the original Uri found in the XAML. If you need the exact original Uri from the XAML, it is found in the _uri field of the BitmapDecoder but you'll need reflection and elevated code permissions to get to it, plus your code may not work in future NET Framework versions.

You could try this:
string path = ((BitmapImage)image.Source).UriSource.AbsolutePath;

Related

Using Bitmap Class in XAML [duplicate]

I have two .png files added to my resources which I need to access their Uri when doing binding.
My xaml code is as followed:
<Grid>
<Image>
<Image.Source>
<BitmapImage DecodePixelWidth="10" UriSource="{Binding Path=ImagePath}"/>
</Image.Source>
</Image>
</Grid>
and the binding code using ImagePath is:
ImagePath = resultInBinary.StartsWith("1") ? Properties.Resources.LedGreen : Properties.Resources.ledRed;
However
Properties.Resources.LedGreen
returns a Bitmap instead of String containing the Uri of that particular image.
I just want to know how to extract that value without a need to address a path of the image in the directory that it's stored. (Which honestly I am not sure is a right thing to do as I couldn't find any similar situation on the net).
Please let me know if there is even a preferred method to the one I am trying to use if available.
In a WPF application you would usually not store images in Properties/Resources.resx and access them by means of the Properties.Resources class.
Instead you just add the image files to your Visual Studio project as regular files, perhaps in a folder named "Images" or the like. Then you would set their Build Action to Resource, which is done in the Properties window. You get there e.g. by right-clicking the image file and select the Properties menu item. Note that the default value of the Build Action should be Resource for image files anyways.
In order to access these image resources from code you would then use a Pack URI. With the above folder name "Images" and an image file named "LedGreen.png", creating such an URI would look like this:
var uri = new Uri("pack://application:,,,/Images/LedGreen.png");
So you could perhaps declare your property to be of type Uri:
public Uri ImageUri { get; set; } // omitted INotifyPropertyChanged implementation
and set it like this:
ImageUri = resultInBinary.StartsWith("1")
? new Uri("pack://application:,,,/Images/LedGreen.png")
: new Uri("pack://application:,,,/Images/LedRed.png");
Finally your XAML should look like shown below, which relies on built-in type conversion from Uri to ImageSource:
<Grid>
<Image Width="10" Source="{Binding Path=ImageUri}" />
</Grid>
Declare the Properties.Resources.LedGreen property as ImageSource and set it to Uri location rather than the Bitmap object.
Or if you insist of storing it as a bitmap you can get the source by returning Properties.Resources.LedGreen.ImageSource which will be of type ImageSource.
I would prefer the first approach.

get image from resource XAML

I have a WPF application, I should set button image depending on current culture. It works fine for strings:
<Label Content="{x:Static res:Resources.Buy}"></Label>
show string depending on culture, but with image:
<Image Source="{x:Static res:Resources.GetItFree}"></Image>
I get an error. Why and how to do correctly?
I have done this before, but using a library: Infralution.Localization.Wpf. It is very simple the way of doing the images resources references:
<Window Language="{UICulture}" x:Class="WpfApp.MainWindow"
...
Icon="{Resx ResxName=WpfApp.MainWindow, Key=Window.Icon}">...</Window>
This is the final image you get (it changes with culture):
Hope this reference could helps, it works for me...

Silverlight - bind to URL

For some reason when I put
"Img/Covers/Medium/106.jpg"
EDIT:
<Image Grid.Column="0" Stretch="None" HorizontalAlignment="Left" Source="Img/Covers/Medium/106.jpg" Margin="7,0,0,0"></Image>
As the Source for an Image, it works perfectly. But when I try to bind the Source to a property defined as such, it doesn't find it.
public virtual Uri MediumImgURI {
get { return new Uri("Img/Covers/Medium/106.jpg"); }
}
EDIT:
<Image Grid.Column="0" Stretch="None" HorizontalAlignment="Left" Source="{Binding Path=MediumImgURI}" Margin="7,0,0,0"></Image>
Is there something special I have to do to get the latter case to work?
EDIT: Also, making that property a string, instead of Uri causes it to work, but this is an over-simplification - I really need to get it to work with the property as Uri.
EDIT:
When I was linking to images that were in my website, and not my SL app, I had this code (which worked)
public virtual string MediumImgURI {
get { return new Uri(App.Current.Host.Source, String.Format("../Img/Medium/{0}.jpg", CurrentBook.smallID)); }
}
When linking instead to an image in my SL app I thought I could just leave off the first parameter, but it appears not.
Yes, hard to tell from what you have posted. It may be that your binding is failing. Try pulling it up in SilverlightSpy3 and see what the Source is for that image.
Sorry everyone - I did a poor job of researching this myself before asking. As noted here,
https://stackoverflow.com/questions/20586/wpf-image-urisource-and-data-binding
it needs to be a Uri relative to the xap file, so I need a ../ in front of my address.
Thanks for answering.

binding an image source in XAML

I am trying to bind an image source to my XAML through c#
this works
<Image Source="images/man.jpg"></Image>
this does not work
<Image Source="images/{Binding imagesource}"></Image>
where imagesource is a string variable in the c# file of this xaml and is being set equal to "man.jpg"
here is a way how to do it in XAML:
add this to the namespace:
xmlns:System="clr-namespace:System;assembly=mscorlib"
then add your images paths
<System:String x:Key="ImageRefresh">/Theme;component/Images/icon_refresh.png</System:String>
<System:String x:Key="ImageSearch">/Theme;component/Images/icon_search.png</System:String>
This is how you use it
<Image Height="16" Source="{StaticResource ImageSearch}" Stretch="Uniform" Width="16"/>
This works ok, but if you load your xaml style in Blend it will go bogus..
An object of type "System.String" cannot be applied to a property that expects the type "System.Windows.Media.ImageSource".
I haven't figured out yet, how to replace System:String with that Media.ImageSource... but hey.. it works for me in Visual Studio.
You can't stick a binding mid-way through the value like that. It's either a binding, or it's not. Assuming imagesource is publicly accessible via your DataContext, you could do this:
<Image Source="{Binding imagesource}"/>
However, if it's been set to "man.jpg" then it won't find the image. Either set imagesource to the full path ("images/man.jpg") or use a converter:
<Image Source="{Binding imagesource, Converter={StaticResource RelativePathConverter}}"/>
The converter would prepend "images/" onto its value. However, it may be necessary for the converter to return an ImageSource rather than a string.
Images have bitten me in the past. There is a certain lookup order involved.
When you use "image/man.jpg" it could refer to a file inside your silverlight xap, or relative to the location of XAP file. For example, it could be in YourProject.Web/ClientBin/image/man.jpg.
You should troubleshoot by using full URLs first and find out if this works.
imagesource needs to be an actual Image object, not a string.
Here is a method that will create a new Image object given a path:
public BitmapImage Load(string path)
{
var uri = new Uri(path);
return new BitmapImage(uri);
}

How can I set the WPF BitmapImage UriSource property to a relative path?

I'm loading an image in WPF by using the BitmapImage class. My code works perfectly when I give an absolute path for the UriSource but not when I try and use a relative path.
My XAML is:
<Image Width="50" Name="MemberImage" HorizontalAlignment="Left">
<Image.Source>
<BitmapImage DecodePixelWidth="50" UriSource="questionmark.jpg" />
</Image.Source>
</Image>
The questionmark.jpg is added to the project with a Build Action of Resource and Copy to Output Directory set to Copy always. The error I get is "The file [file name] is not part of the project or its 'Build Action' property is not set to 'Resource'". This works when I use an absolute path for the UriSource but that obviously won't do.
How should I be defining my UriSource in the XAML?
I don't think you need to copy the image to output directory once it's in resource.
Correct way to specify is
<BitmapImage
x:Key = "Logo"
UriSource = "pack://application:,,,/ApplicationNamespace;component/Images/App/image.png"
/>
Just replace
ApplicationNamespace with your application namespace
and
Images/App/image.png with your image path in the project
Image files with the following options in properties
Build Action=Content
Copy to Output Directory=Copy if newer
<BitmapImage x:Key="QuestionMark" UriSource="pack://siteoforigin:,,,/questionmark.png"/>
Reference:
Xaml - Bitmap UriSource - absolute path works, relative path does not, why?
I cannot reproduce the problem on my computer:
I add the jpg by choosing Add existing item in the Project menu
I then set its Build Actio to Resource and Copy to Output directory to always.
My XAML is the same.
Works perfectly here, even after moving the .exe and renaming the jpg. Something else must be biting you!

Resources