So I have an image that when the user clicks on a button it will change it to a new item. However, whenever the user clicks on one of the button, the window will go blank. How can I get this to work? Thank you.
private void Next_Click(object sender, RoutedEventArgs e)
{
if (imageNumber > 6)
{
imageNumber = 1;
}
imageNumber++;
string sUri = string.Format("#/Resources/{0}", imageSource[imageNumber]);
Uri src = new Uri(sUri, UriKind.Relative);
var bmp = new BitmapImage(src);
img.Source = bmp;
}
xaml
<Image x:Name="img">
<Image.Source>
<BitmapImage UriSource="Resources/BlackJackTut-1.jpg" />
</Image.Source>
</Image>
In WPF application you can do same also with "pack://application:,,,/resources/imagename.png".
This way called Pack URI. This is static, but with these code you can do same an even use resource ;)
Put image in Resources.
private BitmapImage ConvertBitmapToBitmapImage(System.Drawing.Bitmap bitmap)
{
MemoryStream memoryStream = new MemoryStream();
bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = new MemoryStream(memoryStream.ToArray());
bitmapImage.EndInit();
return bitmapImage;
}
and then use this:
private void btn_Click(object sender, RoutedEventArgs e)
{
this.Img.Source = ConvertBitmapToBitmapImage(Properties.Resources.iamge1);
}
Just make an Image outside the mainWindow.
Then:
myImageOnScreen.Source = myImageOffScreen.Source;
Related
I tried this code. I drag Image from WebView to Canvas. But nothing to be show. Maybe dropped data is URL or html data. BUt I don't know how to convert html data to Bitmap data.
private async void drop(object sender, DragEventArgs e)
{
if (e.DataView.Contains(StandardDataFormats.StorageItems))
{
var items = await e.DataView.GetStorageItemsAsync();
if (items.Count > 0)
{
Point drop = e.GetPosition(Board);
var storageFile = items[0] as StorageFile;
var bitmapImage = new BitmapImage();
bitmapImage.SetSource(await storageFile.OpenAsync(FileAccessMode.Read));
Image img = new Image();
img.Source = bitmapImage;
img.Width = 200;
img.Height = 150;
Canvas.SetLeft(img, drop.X);
Canvas.SetTop(img, drop.Y);
Board.Children.Add(img);
}
}
}
XAML is below.
<WebView x:Name="WebView" Source="https://google.com" ScriptNotify="Notify" NavigationCompleted="Completed" ></WebView>
<Canvas AllowDrop="True" DragOver="dragOver" Drop="drop"></Canvas>
I'm trying to add an Image as the background of a UserControl. Depending on the value of a variable I need to change that background but whatever the path or Uri format I use, the background does not change.
I've seen lots of questions here in stackoverflow but none fixes my single problem.
I let the code below:
if (callback.liveUvis.ContainsUVI(uvi))
{
this.Status.Text = "LIVE";
ImageBrush imgB = new ImageBrush();
BitmapImage btpImg = new BitmapImage();
btpImg.UriSource = new Uri(#"///IMG///Live///bck_frame_info_video_live.png", UriKind.Relative);
//imgB.ImageSource = new BitmapImage(new Uri("~/IMG/Live/bck_frame_info_video_live.png", UriKind.RelativeOrAbsolute));
//imgB.ImageSource = new BitmapImage(new Uri("ms-appx:///IMG/Live/bck_frame_info_video_live.png"));
imgB.ImageSource = btpImg;
this.Background = imgB;
}
I'm facing the same problem when trying to attach an image... I guess it's up to the Uri format also, but I let the code too just in case :)
private void setIcon_Desc(string dd)
{
try
{
Image img = new Image();
img.Source = new BitmapImage(new Uri(this.BaseUri, "IMG/pictos_small/white/160dpi/" + dd + ".png"));
img.Stretch = Stretch.None;
this.Icon = img;
this.Sport.Text = callback.disc.getDescription(dd).ToUpper();
}
catch(Exception ex)
{
callback.exception.writeExceptions(ex);
}
}
Thanks in advance!
I can reproduce your issue when changing the background of a user control.
The current workaround I used was changing the background of root UIElement in the control.
<Grid x:Name="container">
<Grid.Background>
<ImageBrush Stretch="Fill" ImageSource="Images/bg-blue.png"/>
</Grid.Background>
<StackPanel>
<TextBlock>Hello World</TextBlock>
<Button Click="Button_Click">Change Background</Button>
<Image x:Name="display"></Image>
</StackPanel>
</Grid>
public sealed partial class MyUserControl : UserControl
{
public MyUserControl()
{
this.InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
ImageBrush imgB = new ImageBrush();
BitmapImage btpImg = new BitmapImage();
btpImg.UriSource = new Uri(#"ms-appx:///images/bg-light-blue.png");
imgB.ImageSource = btpImg;
container.Background = imgB;
}
}
I have a button b3 and an image named pictureBox1 . Im using WPF, however I'm using the winforms openFileDialog instead of the one that comes with WPF :
below is the code that I put inside the click event of my button :
private void b3_Click(object sender, RoutedEventArgs e)
{
System.Windows.Forms.OpenFileDialog openDialogIcon = new System.Windows.Forms.OpenFileDialog();
if (openDialogIcon.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
Image i = new Image();
BitmapImage src = new BitmapImage();
src.BeginInit();
src.UriSource = new Uri(openDialogIcon.FileName, UriKind.Absolute);
src.CacheOption = BitmapCacheOption.OnLoad;
src.EndInit();
i.Source = src;
i.Stretch = Stretch.Uniform;
//int q = src.PixelHeight; // Image loads here
}
}
When I click the button and select an icon. The icon doesn't appear in the pictureBox1.
Can someone please explain why the code above doesn't show the icon inside the pictureBox?
You need to assign your image to the pictureBox, else you wont see it on your screen and you only made the image object in memory.
private void b3_Click(object sender, RoutedEventArgs e)
{
System.Windows.Forms.OpenFileDialog openDialogIcon = new System.Windows.Forms.OpenFileDialog();
if (openDialogIcon.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
BitmapImage src = new BitmapImage();
src.BeginInit();
src.UriSource = new Uri(openDialogIcon.FileName, UriKind.Absolute);
src.CacheOption = BitmapCacheOption.OnLoad;
src.EndInit();
pictureBox1.Source = src;
}
}
Try to drag and drop a Image control in your window
...
//imageStretch <- the name of Image control
i.Stretch = Stretch.Uniform;
//int q = src.PixelHeight; // Image loads here
imageStretch.Source = src;
...
Using Photochooser Task the image has to be loaded and passed immediately to another page. But shows blank when implemented the following code:
private void LoadPicture_Click(object sender, RoutedEventArgs e)
{
PhotoChooserTask photoChooserTask;
photoChooserTask = new PhotoChooserTask();
photoChooserTask.Completed += new EventHandler<PhotoResult>(photoChooserTask_Completed);
photoChooserTask.Show();
NavigationService.Navigate(new Uri("/Page1.xaml", UriKind.Relative));
}
void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
bmp.SetSource(e.ChosenPhoto);
Page1 p1 = new Page1();
p1.encodeImg.Source = bmp;
}
else
{
MessageBox.Show("Image Loading Failed.");
}
}
Please suggest in fixing the above the issue.
Thanks!
Have you solved it? if you haven't you could use something like this. in your photoChooseTask handler save the bitmapImage
PhoneApplicationService.Current.State["yourparam"] = bmp;
and then in your Page1 you get the bitmapImage
BitmapImage bitmapGet = PhoneApplicationService.Current.State["yourparam"] as BitmapImage;
here's how you should use this.
void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
bmp.SetSource(e.ChosenPhoto);
//save the bitmapImage
PhoneApplicationService.Current.State["yourparam"] = bmp;
}
else
{
MessageBox.Show("Image Loading Failed.");
}
NavigationService.Navigate(new Uri("/Page1.xaml", UriKind.Relative));
}
your Page1
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
//get the bitmapImage
BitmapImage bitmapGet = PhoneApplicationService.Current.State["yourparam"] as BitmapImage;
//set the bitmpaImage
img.Source = bitmapGet;
base.OnNavigatedTo(e);
}
More about PhoneApplicationService.Current.State :)
The navigation must be done after completed event, photochooser.show() suppresses the main application thread, hence you can only pass the image stream once you get it. So, shift navigation statement to completed event handler and using isolatedstoragesettings.applicationsettings to store the image and get it back on second page.
Another way to achieve it is to save the image in isolateStorage first and pass the file path to your page1 as a string parameter.
page1 then could load the image anytime it needs.
i need to insert an image in a WP8. i have a stack of images. once i click the image, it has to be set as background for a grid. so i created an empty "grid1" and button. wrote the below code in the button click event, but the image doesnot get displayed !
private void bg6_Click(object sender, RoutedEventArgs e)
{
System.Windows.Media.ImageBrush myBrush = new System.Windows.Media.ImageBrush();
Image image = new Image();
image.Source = new System.Windows.Media.Imaging.BitmapImage(
new Uri("\\PhoneApp2\\PhoneApp2\\Assets\\bg\\bg5.jpg"));
myBrush.ImageSource = image.Source;
// Grid grid1 = new Grid();
grid1.Background = myBrush;
}
It is hard to know if your image file is in the correct place and set to the right build type. I'd suggest adding an event handler to the Image failed event.
private void bg6_Click(object sender, RoutedEventArgs e)
{
System.Windows.Media.ImageBrush myBrush = new System.Windows.Media.ImageBrush();
Image image = new Image();
image.ImageFailed += (s, e) => MessageBox.Show("Failed to load: " + e.ErrorException.Message);
image.Source = new System.Windows.Media.Imaging.BitmapImage(
new Uri("\\PhoneApp2\\PhoneApp2\\Assets\\bg\\bg5.jpg"));
myBrush.ImageSource = image.Source;
// Grid grid1 = new Grid();
grid1.Background = myBrush;
}
First, you don't need to use Image to fill the background from URI.
private void bg6_Click(object sender, RoutedEventArgs e)
{
System.Windows.Media.ImageBrush myBrush = new System.Windows.Media.ImageBrush(new Uri("\\PhoneApp2\\PhoneApp2\\Assets\\bg\\bg5.jpg"));
// Grid grid1 = new Grid();
grid1.Background = myBrush;
}
Second, it is a WAY better to design it in XAML and manipulate it visibility and source from code by creating the helper class with visibility and source property. Don't forget to implement INotifyPropertyChanged interface into that class.
<Grid x:Name="myGrid" DataContext="{Binding}" Visibility="{Binding Path=VisibleProperty}">
<Grid.Background>
<ImageBrush x:Name="myBrush" ImageSource="{Binding Path=SourceProperty}"></ImageBrush>
</Grid.Background>
And in code:
private void bg6_Click(object sender, RoutedEventArgs e)
{
myGrid.DataContext=new myImagePresenterClass(new Uri("\\PhoneApp2\\PhoneApp2\\Assets\\bg\\bg5.jpg"), Visibility.Visible)
}
public class myImagePresenterClass:INotifyPropertyChanged
{
private URI sourceProperty
Public URI SourceProperty
{
get
{
return sourceProperty;
}
set
{
sourceProperty=value;
if(PropertyChanged!=null){PropertyChanged(this, new PropertyChangedEventArgs("SourceProperty"));}
}
}
//Don't forget to implement the Visible property the same way as SourceProperty and the class constructor.
}
i found the mistake... i'm sorry guys. i didn't follow the syntax correctly. i missed the '#' in the Uri method. the correct way to represent this is
private void bg1_Click(object sender, RoutedEventArgs e)
{
System.Windows.Media.ImageBrush myBrush = new System.Windows.Media.ImageBrush();
Image image = new Image();
image.ImageFailed += (s, i) => MessageBox.Show("Failed to load: " + i.ErrorException.Message);
image.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri(#"/Assets/bg/bg1.jpg/", UriKind.RelativeOrAbsolute));
myBrush.ImageSource = image.Source;
grid1.Background = myBrush;
}