Load PNG from code behind [duplicate] - c#

It seems like it's quite complicated to load an image in runtime to a WPF window.
Image image;
image = new Uri("Bilder/sas.png", UriKind.Relative);
????.Source = new BitmapImage(image);
I'm trying this code, but I need some help to get it to work. I get some red lines below the code! I also wonder if I need to add some extra code inside the XAML code or is in enough with this:
<Image Height="200" HorizontalAlignment="Left" Margin="12,12,0,0" Name="image1"
Stretch="Fill" VerticalAlignment="Top" Width="350" />
Wonder because I have seen examples with sorces to the images inside the XAML tags.
EDIT:
I'm using this now:
var uri = new Uri("pack://application:,,,/sas.png");
var bitmap = new BitmapImage(uri);
image1.Source = bitmap;
The XAML:
<Grid Width="374">
<Image Height="200" HorizontalAlignment="Left" Margin="12,12,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="350" />
<Button Content="Start" Height="23" HorizontalAlignment="Left" Margin="12,226,0,0" Name="btnStart" VerticalAlignment="Top" Width="75" />
<Button Content="Land" Height="23" HorizontalAlignment="Left" Margin="287,226,0,0" Name="btnLand" VerticalAlignment="Top" Width="75" />
<ComboBox Height="23" HorizontalAlignment="Left" Margin="110,226,0,0" Name="cmbChangeRoute" VerticalAlignment="Top" Width="156" />
</Grid>
EDIT 2:
My issue is solved, this code works fine:
BitmapImage image = new BitmapImage(
new Uri("pack://application:,,,/Resources/" + company + ".png"));
image2.Source = image;

In WPF an image is typically loaded from a Stream or an Uri.
BitmapImage supports both and an Uri can even be passed as constructor argument:
var uri = new Uri("http://...");
var bitmap = new BitmapImage(uri);
If the image file is located in a local folder, you would have to use a file:// Uri. You could create such a Uri from a path like this:
var path = Path.Combine(Environment.CurrentDirectory, "Bilder", "sas.png");
var uri = new Uri(path);
If the image file is an assembly resource, the Uri must follow the the Pack Uri scheme:
var uri = new Uri("pack://application:,,,/Bilder/sas.png");
In this case the Visual Studio Build Action for sas.png would have to be Resource.
Once you have created a BitmapImage and also have an Image control like in this XAML
<Image Name="image1" />
you would simply assign the BitmapImage to the Source property of that Image control:
image1.Source = bitmap;

Make sure that your sas.png is marked as Build Action: Content and Copy To Output Directory: Copy Always in its Visual Studio Properties...
I think the C# source code goes like this...
Image image = new Image();
image.Source = (new ImageSourceConverter()).ConvertFromString("pack://application:,,,/Bilder/sas.png") as ImageSource;
and XAML should be
<Image Height="200" HorizontalAlignment="Left" Margin="12,12,0,0"
Name="image1" Stretch="Fill" VerticalAlignment="Top"
Source="../Bilder/sas.png"
Width="350" />
EDIT
Dynamically I think XAML would provide best way to load Images ...
<Image Source="{Binding Converter={StaticResource MyImageSourceConverter}}"
x:Name="MyImage"/>
where image.DataContext is string path.
MyImage.DataContext = "pack://application:,,,/Bilder/sas.png";
public class MyImageSourceConverter : IValueConverter
{
public object Convert(object value_, Type targetType_,
object parameter_, System.Globalization.CultureInfo culture_)
{
return (new ImageSourceConverter()).ConvertFromString (value.ToString());
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Now as you set a different data context, Image would be automatically loaded at runtime.

Related

How to put an Image in WPF Window [duplicate]

It seems like it's quite complicated to load an image in runtime to a WPF window.
Image image;
image = new Uri("Bilder/sas.png", UriKind.Relative);
????.Source = new BitmapImage(image);
I'm trying this code, but I need some help to get it to work. I get some red lines below the code! I also wonder if I need to add some extra code inside the XAML code or is in enough with this:
<Image Height="200" HorizontalAlignment="Left" Margin="12,12,0,0" Name="image1"
Stretch="Fill" VerticalAlignment="Top" Width="350" />
Wonder because I have seen examples with sorces to the images inside the XAML tags.
EDIT:
I'm using this now:
var uri = new Uri("pack://application:,,,/sas.png");
var bitmap = new BitmapImage(uri);
image1.Source = bitmap;
The XAML:
<Grid Width="374">
<Image Height="200" HorizontalAlignment="Left" Margin="12,12,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="350" />
<Button Content="Start" Height="23" HorizontalAlignment="Left" Margin="12,226,0,0" Name="btnStart" VerticalAlignment="Top" Width="75" />
<Button Content="Land" Height="23" HorizontalAlignment="Left" Margin="287,226,0,0" Name="btnLand" VerticalAlignment="Top" Width="75" />
<ComboBox Height="23" HorizontalAlignment="Left" Margin="110,226,0,0" Name="cmbChangeRoute" VerticalAlignment="Top" Width="156" />
</Grid>
EDIT 2:
My issue is solved, this code works fine:
BitmapImage image = new BitmapImage(
new Uri("pack://application:,,,/Resources/" + company + ".png"));
image2.Source = image;
In WPF an image is typically loaded from a Stream or an Uri.
BitmapImage supports both and an Uri can even be passed as constructor argument:
var uri = new Uri("http://...");
var bitmap = new BitmapImage(uri);
If the image file is located in a local folder, you would have to use a file:// Uri. You could create such a Uri from a path like this:
var path = Path.Combine(Environment.CurrentDirectory, "Bilder", "sas.png");
var uri = new Uri(path);
If the image file is an assembly resource, the Uri must follow the the Pack Uri scheme:
var uri = new Uri("pack://application:,,,/Bilder/sas.png");
In this case the Visual Studio Build Action for sas.png would have to be Resource.
Once you have created a BitmapImage and also have an Image control like in this XAML
<Image Name="image1" />
you would simply assign the BitmapImage to the Source property of that Image control:
image1.Source = bitmap;
Make sure that your sas.png is marked as Build Action: Content and Copy To Output Directory: Copy Always in its Visual Studio Properties...
I think the C# source code goes like this...
Image image = new Image();
image.Source = (new ImageSourceConverter()).ConvertFromString("pack://application:,,,/Bilder/sas.png") as ImageSource;
and XAML should be
<Image Height="200" HorizontalAlignment="Left" Margin="12,12,0,0"
Name="image1" Stretch="Fill" VerticalAlignment="Top"
Source="../Bilder/sas.png"
Width="350" />
EDIT
Dynamically I think XAML would provide best way to load Images ...
<Image Source="{Binding Converter={StaticResource MyImageSourceConverter}}"
x:Name="MyImage"/>
where image.DataContext is string path.
MyImage.DataContext = "pack://application:,,,/Bilder/sas.png";
public class MyImageSourceConverter : IValueConverter
{
public object Convert(object value_, Type targetType_,
object parameter_, System.Globalization.CultureInfo culture_)
{
return (new ImageSourceConverter()).ConvertFromString (value.ToString());
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Now as you set a different data context, Image would be automatically loaded at runtime.

Call GIF image source from the code behind in WPF c# for the tabcontrol's setter

i am using wpf tab control and setting the Icon and text in the tab header through style, i am able to set the text dynamically through getter and setter but can not able to set the image source. I tried to bind the image source through getter and setter but failed. Following is the style code in which i want to set the image source dynamically from the code behind.
-->
<Setter Property="HeaderTemplate" >
<Setter.Value>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<!--<Image gif:ImageBehavior.AnimatedSource="{DynamicResource MyFillBrush}" Width="20" />-->
<Image gif:ImageBehavior.AnimatedSource="25.gif" Width="20" />
<Label Content="{Binding }"/>
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
I know this is a bit old thread, but this is how you update the AnimatedSource from code:
var image = new BitmapImage();
image.BeginInit();
image.UriSource = new Uri(value);
image.EndInit();
ImageBehavior.SetAnimatedSource(Imagereference, image);
The 'value' is the location of your gif file such as "25.gif".
The Imagereference is the Image control you want to update. Also ensure you have the namespace referenced: using WpfAnimatedGif;
Maybe you can use Binding, something like
private string _dynamicGif = "test.gif";
public string DynamicGif
{
get { return _dynamicGif; }
private set
{
_dynamicGif = value;
RaisePropertyChanged("DynamicGif");
}
}
and
<Image gif:ImageBehavior.AnimatedSource="{Binding DynamicGif, UpdateSourceTrigger=PropertyChanged}" Width="20" />
Or, if it doesn't work, you can use MediaElement instead of Image, it won't require WPF Animated GIF. It's also pretty simple to use:
private Uri _imgSource = new Uri("test.gif");
public Uri ImgSource
{
get { return _imgSource; }
private set
{
_imgSource = value;
RaisePropertyChanged("ImgSource");
}
}
and
<MediaElement x:Name="gifImg" LoadedBehavior="Play" Width="20" Source="{Binding ImgSource}"/>
Hope this helps.

Programmatically setting Image.Source property: I get an empty image

I have a folder inside my project which includes some images, for example: "Cards/1-1.png".
I have an Image element linked with XAML, and I'm trying to set it's Source property programmatically:
BitmapImage bitmap = new BitmapImage();
string filename= "Cards/1-1.png";
bitmap.UriSource = new Uri("/Poker;component/" + filename, UriKind.Relative);
cardImage1.Source= bitmap; // myImage linked with XAML
I try to fill 5 images, and I checked the filenames, they're correct. But the images are still empty (they're inside the StackPanel on the right):
<StackPanel Orientation="Horizontal" DockPanel.Dock="Right"
Background="Green">
<Image Width="80" Height="100" Margin="10" x:Name="cardImage1"/>
<Image Width="80" Height="100" Margin="10" x:Name="cardImage2"/>
<Image Width="80" Height="100" Margin="10" x:Name="cardImage3"/>
<Image Width="80" Height="100" Margin="10" x:Name="cardImage4"/>
<Image Width="80" Height="100" Margin="10" x:Name="cardImage5"/>
</StackPanel>
BitmapImage implements ISupportInitialize interface which means any property change after initialization of object will be ignored unless wrap in BeginInit() and EndInit().
Quote from MSDN:
BitmapImage implements the ISupportInitialize interface to optimize
initialization on multiple properties. Property changes can only occur
during object initialization. Call BeginInit to signal that
initialization has begun and EndInit to signal that initialization has
completed. After initialization, property changes are ignored.
BitmapImage objects created using the BitmapImage constructor are
automatically initialized and property changes are ignored.
So, change your code to wrap property initialization like this:
BitmapImage bitmap = new BitmapImage();
string filename= "Cards/1-1.png";
bitmap.BeginInit();
bitmap.UriSource = new Uri("/Poker;component/" + filename, UriKind.Relative);
bitmap.EndInit();
cardImage1.Source= bitmap; // myImage linked with XAML
OR
Initialize all relevant properties at time of initialization by passing Uri in constructor like this:
string filename= "Cards/1-1.png";
BitmapImage bitmap = new BitmapImage(new Uri("/Poker;component/" + filename,
UriKind.Relative));
I tried this code but it isn't working, i found a way to do what you exactly need:
cardImage1.Source = new BitmapImage(new Uri("/Poker;component/" + filename, UriKind.Relative));
you assigned BitmapImage.Source to Image.Source, i think that's why it isn't working.
Hope it helps.

How to bind xml image in listbox in windows phone 8

How to bind xml image in windows phone 8?
I have done all methods but its not working, Whenever I debug the application, it contains source of an Image but, image is not displaying.
Code:
List<LIST> lst = new List<LIST>();
lst = (from query in doc.Descendants("row") select new LIST
{ Id = Convert.ToInt64(query.Element("Id").Value),
Icon = query.Element("Icon").Value,
xyz = Convert.ToInt64(query.Element("xyz").Value),
Url = query.Element("Url").Value, Name = query.Element("Name").Value }).ToList();
listBox1.DataContext = lst;
XAML Code:
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Icon}" Stretch="Uniform" HorizontalAlignment="Center" Height="50" Width="50" VerticalAlignment="Top"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
I think you can try to use a Converter (if you search internet for Binding and Converter, you will find many links, tutorials etc.). A simple code can look like this (I haven't tried it):
In XAML:
...
xmlns:common="clr-namespace:YourNamespace"
...
<phone:PhoneApplicationPage.Resources>
<common:ToImageSource x:Key="converter"/>
</phone:PhoneApplicationPage.Resources>
...
<Image Source="{Binding Icon, Converter={StaticResource converter} }" Stretch="Uniform" HorizontalAlignment="Center" Height="50" Width="50" VerticalAlignment="Top"/>
In .cs:
public class ToImageSource : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null) return null;
else
{
byte[] imageBytes = Convert.FromBase64String(value);
using (MemoryStream stream = new MemoryStream(imageBytes, 0, imageBytes.Length))
{
stream.Write(imageBytes, 0, imageBytes.Length);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(stream);
return bitmap;
}
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{ // implement ConvertBack }
}
You can also read more about binding and converters at MSDN.
Here is my .cs file:
public static BitmapImage getImage(string img)
{
byte[] filebytes = Convert.FromBase64String(img);
MemoryStream ms = new MemoryStream(filebytes, 0, filebytes.Length);
BitmapImage image = new BitmapImage();
image.SetSource(ms);
return image;
}
Icon = getImage(query.Element("Icon").Value);
and XAML file:
<Image Source="{Binding Icon}" Stretch="Uniform" HorizontalAlignment="Center" Height="50" Width="50" VerticalAlignment="Top"/>

bind absolute images to longlistselector in mvvm

I have downloaded a set of items from a web site and got text details into a binding class. In these i have image uri which i need to bind to the longlist selector along with other details. The problem is that I am not able to download, indeed there has been an exception in design view when i place a image converter itself.
Converter code:
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var imageFile = value as string;
if (imageFile != null)
{
BitmapImage image = new BitmapImage();
image.CreateOptions = BitmapCreateOptions.BackgroundCreation;
image.UriSource = new Uri("http://www.somewebsite.com/" + imageFile, UriKind.Absolute);
return image;
}
else
return null;
}
LLS:
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<Grid Height="500" Margin="0,0,0,12">
<Grid.Resources>
<local:ImageConverter x:Name="imageConverter"/>
</Grid.Resources>
<Grid.Background>
<ImageBrush Stretch="Uniform" ImageSource="{Binding Path=ImgSrc, Converter={StaticResource imageConverter}}"/>
</Grid.Background>
You really don't need to download it yourself. Just bind to the path string.
<DataTemplate>
<Grid Height="500" Margin="0,0,0,12">
<Grid.Background>
<ImageBrush Stretch="Uniform" ImageSource="{Binding ImgSrc}"/>
</Grid.Background>
</Grid>
</DataTemplate>

Categories