I am trying to add images that I get from my webcam to gridview however each time I get exception. I have separate page to make a picture from webcam and later, I pass image full path to other page. Here are the code snippets:
C#
protected override void OnNavigatedTo(NavigationEventArgs e)
{
//If navigated from PhotoCapturePage
if (m_ToBeNavigatedPageType == typeof(PhotoCapturePage))
{
if (e.Parameter == null)
{
return;
}
Image img = new Image();
img.Width = 64;
img.Height = 64;
img.Source = new BitmapImage(new Uri(e.Parameter.ToString()));
IncidentPictures.Add(img);
IncidentPictureGrid.Items.Add(img);
}
}
XAML:
<GridView ItemsSource="{Binding IncidentPictures}" Name="IncidentPictureGrid" Width="350"></GridView>
Each time IncidentPictureGrid.Items.Add(img) is performed, I receive Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED)) exception.
Does anyone has suggestions?
Thanks in advance,
Miroslawas
Why do you add the image to the Grid.Items collection when you add it to IncidentPictures collection too?
You already bind the GridView's ItemsSource to the collection. Maybe this cause the error ... Remove the IncidentPictureGrid.Items.Add and make sure, that IncidentPictures is an ObservableCollection.
Related
I'm trying to display an animated GIF on a form from an embedded resource, yet nothing is displayed, which makes me think loading from a stream doesn't work this way.
If I ditch this idea and load from file, the GIF is displayed correctly.
Is this something that just won't work, or have I made a mistake along the way? Also, this is being done from within a DLL.
My Code:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// Set the image
this.pictureBox.Image = GetImageFromManifest("TempNamespace.Wait.gif");
// Remove the close button
var hwnd = new WindowInteropHelper(this).Handle;
SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU);
}
public System.Drawing.Image GetImageFromManifest(string sPath)
{
// Ready the return
System.Drawing.Image oImage = null;
try
{
// Get the assembly
Assembly oAssembly = Assembly.GetAssembly(this.GetType());
string[] names = oAssembly.GetManifestResourceNames();
// Get the stream
Stream oStream = oAssembly.GetManifestResourceStream(sPath);
// Read from the stream
oImage = System.Drawing.Image.FromStream(oStream);
}
catch (Exception ex)
{
// Missing image?
}
//Return the image
return oImage;
}
My XAML:
<wfi:WindowsFormsHost HorizontalAlignment="Center" VerticalAlignment="Center" Height="50" Width="50">
<winForms:PictureBox x:Name="pictureBox" Height="50" Width="50" SizeMode="StretchImage" BackgroundImageLayout="None"/>
</wfi:WindowsFormsHost>
In summary, the problem was caused by setting the form's 'SizeToContent' value in either the XAML or the constructor (in my case, it was set to 'SizeToContent.WidthAndHeight').
Removing this property, and setting it in the 'Loaded' event rectified the issue. I assume that the Windows Form Host doesn't render correctly with animated GIF files when the form itself is not painted.
I'm a novice programmer so don't be brutal.
I'm making a game for Windows Store, and I want to animate a run cycle. I made many GIF animations but all have BLACK background, and I need it transparent. So I've decided to make a run cycle using DispatcherTimer. Everything works fine, but the images don't change :/
void timer_Tick(object sender, object e)
{
numer++;
if (numer > 8) numer = 1;
hero.Source.Equals("Assets/Anim/" + nazwa + numer + ".png");
}
Also, When I TAP a different image, it should change the image and other images, but it doesn't... what is wrong?
bool sun = true;
private void Image_Tapped(object sender, TappedRoutedEventArgs e)
{
sun = !sun;
if (sun == false)
{
Image1.Source.Equals("moon.png");
Image2.Source.Equals("ON.png");
}
else
{
Image1.Source.Equals("sun.png");
Image2.Source.Equals("OFF.png");
}
}
The xaml works fine, as the images are shown.
I have checked this question:
ImageTools on Windows Phone 8, changing ImageSource and DataContext
but I get loads of errors. I don't seem to understand how the property changed works.
it seems to be a small mistake. You are using the wrong method.
Image.Source.Equals()
is a boolean method that simply compares the current source with the "source" you give as arguement and will return true or false based on the comparison.
But what you want is to set the source of the image.
So you need to use:
Image1.Source = new BitmapImage(new Uri("moon.png", UriKind.RelativeOrAbsolute));
This will set the source of the Image to the new image you want.
Assuming that "moon.png" is in the main folder in your solution, the two solutions both work:
BitmapImage tn = new BitmapImage();
tn.SetSource(Application.GetResourceStream(new Uri(#"moon.png", UriKind.Relative)).Stream);
Image1.Source = tn;
Or
Image1.Source = new BitmapImage(new Uri("moon.png", UriKind.Relative));
Good morning everyone!
I've been having some issues regarding photos in my Windows Phone app. I'm trying to take a photo and save it to a record, and then load it up again at a different point.
My idea is to take the photo using the code in this tutorial (http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006(v=vs.105).aspx)
In my constructor:
cameraCaptureTask = new CameraCaptureTask();
cameraCaptureTask.Completed += new EventHandler<PhotoResult>(cameraCaptureTask_Completed);
lower down..
void cameraCaptureTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
//Code to display the photo on the page in an image control named myImage.
//System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
//bmp.SetSource(e.ChosenPhoto);
//System.Diagnostics.Debug.WriteLine(e.OriginalFileName);
//string imageLoc = e.OriginalFileName;
//Uri imageUri = new Uri(imageLoc, UriKind.RelativeOrAbsolute);
//StreamResourceInfo resourceInfo = Application.GetResourceStream(imageUri);
//Code I'm using just now which just displays the photograph
System.Windows.Media.Imaging.BitmapImage bmp2 = new System.Windows.Media.Imaging.BitmapImage();
bmp2.SetSource(e.ChosenPhoto);
myImage.Source = bmp2;
}
}
From my code, you can see that the commented out bit returns the location of the image which has just been taken, then attempts to load it up from there. However, when I try that, I get URI path exceptions and the like. What is going wrong here and what method should I use to remedy it?
I'd like to be able to add the file path to a record and then be able to load it back up elsewhere in my app.
Thanks for any help!
I am making a simple metro app to display an image and some content relevant to the image.
Ex :
image : data
img1 : "Image of a butterfly"
img2 : "Hello sky"
img3 : "Picture of a Golden Retriever"
I have loaded images into a flipview.And relevent data into an array.
<FlipView HorizontalAlignment="Left" Margin="102,147,0,0" VerticalAlignment="Top" Width="627" Height="429" Name="fiImage" SelectionChanged="fiImage_SelectionChanged">
<Image Source="Assets/image1.png" Name="Img1" />
<Image Source="Assets/image2.png" Name="Img2" />
</FlipView>
I have a TextBlock in the xaml named as "tbN". What I want to do is when I change the image using pointer, relevant data should display in the textblock.
I tried following code at selection change event
private void fiImage_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int i = ((FlipView)sender).SelectedIndex;
tbN.Text = a[i]; //error line
}
But when I execute the program, I get an error saying "NullReferenceException was unhandled by the user code: Object reference not set to an instance of an object."
What am I missing?
It seems a[i] has not being initialized and doesn't have values. Is it a global variable?.
Debug your code and check it's content. It must be null.
If it is not null, maybe that array doesn't have the i value. Or maybe it's exceding the array length.
tbN.Text = a[i]; //a[i] must be null, where is it initialized?
SelectionChanged event fires at initialization as well (first child "selected").
Your control (tbN) does not exist at the time.
Check if tbN is null to avoid NRef. Exception!
private void fiImage_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (tbN != null)
{
int i = ((FlipView)sender).SelectedIndex;
tbN.Text = a[i];
}
}
I've found the solution HERE
private void FlipView_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
FlipView fv = sender as FlipView;
if (fv.SelectedItem == null) return;
var item = fv.ItemContainerGenerator.ContainerFromItem(fv.SelectedItem);
if (item == null)
{
Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
var itemSecondTime = fv.ItemContainerGenerator.ContainerFromItem(fv.SelectedItem);
if (itemSecondTime == null)
{
throw new InvalidOperationException("no item. Why????");
}
});
}
}
I want to iterate through all the files in a folder and dynamically create images controls for each JPEG file found. Once complete I want a form filled with dynamically created image controls (think of just about any photo viewing software such as Picasa that has a thumbnail view).
I want to be able to reorder these dynamically created images controls on the form by implementing some sort of drag drop event handler. I will not know how many images I will encounter and therefore cannot hardcode event handlers for each image control that might or might not exist. So I am looking for a way to dynamically add event handlers to dynamically created controls.
The method used in the code below is almost what I am looking for. The problem with the method below is that if I don't know the name of the control I could not hard code the event handler.
public partial class RoutedEventAddRemoveHandler {
void MakeButton(object sender, RoutedEventArgs e)
{
Button b2 = new Button();
b2.Content = "New Button";
// Associate event handler to the button. You can remove the event
// handler using "-=" syntax rather than "+=".
b2.Click += new RoutedEventHandler(Onb2Click);
root.Children.Insert(root.Children.Count, b2);
DockPanel.SetDock(b2, Dock.Top);
text1.Text = "Now click the second button...";
b1.IsEnabled = false;
}
void Onb2Click(object sender, RoutedEventArgs e)
{
text1.Text = "New Button (b2) Was Clicked!!";
}
}
Note I am looking for a solution in c# code not XAML. That is a solution using code like this to add controls:
// What I want
Fields.Add(new Field() { Name = "Username", Length = 100, Required = true });
not like this:
// What I do not want
<TextBox Width="100" Canvas.Left="50" Canvas.Top="20" />
Thanks
I would not do so much in codebehind. Only to get the files.
I would get an ObservableCollection where the string is the FullName of the file.
Then I would present it in a ListBox or ListView having the ItemSource bound to the collection and defining å good ItemTemplate for the control.
In the template, you can use a Converter to create å Source for the Image in the template.
Adding a small sample just to save you the pain of image loading in WPF code-behind.
void OnButtonClick(object sender, RoutedEventArgs routedEventArgs)
{
var files = Directory.GetFiles(#"C:\img");
foreach (var file in files)
{
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = new Uri(file);
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.EndInit();
var img = new Image { Source = bitmap };
img.MouseDown += OnImageMouseDown;
//Add img to your container
}
}
void OnImageMouseDown(object sender, MouseButtonEventArgs e)
{
var img = sender as Image;
//Operate
}