Setting Image source programatically in Metro app, Image doesn't appear - c#

I have a main page and a camera page in my application. The main page has an image that does not have its source set and a button. If you click the button, it will take you to the camera page. On the camera page, I capture an image and save it in the pictures library on the tablet and then navigate back to the main page where I would like to set the source of the image to the image I just captured and saved in my pictures library. Here is my relevant code.
MainPage.xaml
<Image x:Name="imgResume" HorizontalAlignment="Left" Height="303" Margin="975,60,0,0" Grid.Row="1" VerticalAlignment="Top" Width="360" Stretch="UniformToFill" Loaded="img_OnLoaded"/>
<Button x:Name="btnCamera" Content="Camera" HorizontalAlignment="Left" Margin="1128,372,0,0" Grid.Row="1" VerticalAlignment="Top" RenderTransformOrigin="2.05800008773804,0.184000000357628" Height="59" Width="108" Click="Camera_Click" IsEnabled="False"/>
MainPage.xaml.cs
private void img_OnLoaded(object sender, RoutedEventArgs e)
{
if (txtFirstName.Text != "" && txtLastName.Text != "")
{
try
{
imgResume.Source = ImageFromRelativePath(this, Windows.Storage.KnownFolders.PicturesLibrary.Path + ((App)Application.Current).candidate.FirstName + ((App)Application.Current).candidate.FirstName + "Resume.jpg");
imgResume.UpdateLayout();
}
catch
{
imgResume.Source = ImageFromRelativePath(this, #"Assets/logo.png");
imgResume.UpdateLayout();
}
btnCamera.IsEnabled = true;
}
}
public static BitmapImage ImageFromRelativePath(FrameworkElement parent, string path)
{
var uri = new Uri(parent.BaseUri, path);
BitmapImage result = new BitmapImage();
result.UriSource = uri;
return result;
}
Camera.xaml.cs
private async void Capture_Click(object sender, RoutedEventArgs e)
{
if (mediaCaptureMgr != null)
{
string firstName = ((App)Application.Current).candidate.FirstName;
string lastName = ((App)Application.Current).candidate.LastName;
string fileName = firstName + lastName + "Resume.jpg";
Windows.Storage.IStorageFile photo = await Windows.Storage.KnownFolders.PicturesLibrary.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.ReplaceExisting);
await mediaCaptureMgr.CapturePhotoToStorageFileAsync(Windows.Media.MediaProperties.ImageEncodingProperties.CreateJpeg(), photo);
this.Frame.Navigate(typeof(BasicPersonalInfo));
}
}
The img_OnLoaded method in the MainPage.xaml file is attempting to set the image source to the image that I save to the pictures library from the Capture_click method in the Camera.xaml.cs.
My problem is that the picture never shows up on the image on the first page! Please help!

This may also be helpful to people trying to solve the related problem of updating an Image from a local resource file.
myImage.Source = ImageFromRelativePath(this, "relative_path_to_file_make_sure_build_set_to_content");
public static BitmapImage ImageFromRelativePath(FrameworkElement parent, string path)
{
var uri = new Uri(parent.BaseUri, path);
BitmapImage result = new BitmapImage();
result.UriSource = uri;
return result;
}
Code is from here.

I think this part is the problem:
var uri = new Uri(parent.BaseUri, path);
That seems to try to load the image from the installation folder while your path is a full path, which I believe is not supported for opening files in WinRT and certainly does not work as a Uri even with a baseUri.
You should instead do something like:
var file = await Windows.Storage.KnownFolders.PicturesLibrary.GetFileAsync(((App)Application.Current).candidate.FirstName + "Resume.jpg");
var stream = await file.OpenReadAsync();
var bi = new BitmapImage();
bi.SetSource(stream);
return bi;

Related

UWP drag and drop from WebView onto Canvas

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>

Attach Image/ImageBrush from code behind

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

how save image to folder from Image control Win 8 apps

I have a Image control
<Image Name="img" HorizontalAlignment="Left" Height="400" Margin="499,155,0,0" VerticalAlignment="Top" Width="400"/>
And I capture photo from Camera
private async void TakePhoto_Click(object sender, RoutedEventArgs e)
{
CameraCaptureUI camera = new CameraCaptureUI();
camera.PhotoSettings.CroppedAspectRatio = new Size(4, 3);
var photo = await camera.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (photo != null)
{
BitmapImage image = new BitmapImage();
image.SetSource(await photo.OpenAsync(FileAccessMode.Read));
img.Source = image;
}
}
And now I want to save this image from img control to folder, but I don't know how decode image from img control to StorageFile
private async void SaveFile_Click(object sender, RoutedEventArgs e)
{
FileSavePicker savePicker = new FileSavePicker();
savePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
savePicker.FileTypeChoices.Add("jpeg image", new List<string>() { ".jpeg" });
savePicker.SuggestedFileName = "New picture";
StorageFile ff = await savePicker.PickSaveFileAsync();
if (ff != null)
{
await photo.MoveAndReplaceAsync(ff);
}
}
this is a save method, which i want to save image from Image control
The
var photo = await camera.CaptureFileAsync(CameraCaptureUIMode.Photo); returns a StorageFile. All you have to do is save it to the location you want.
You can accomplish this in may ways.
Example:
StorageFolder localFolder = ApplicationData.Current.LocalFolder; // the app's local storage folder
await photo.MoveAsync(localFolder); //move the file to a new location
2.
//Create a new copy in a new location
await photo.CopyAsync(localFolder);
Note that var photo == StorageFile photo. This means that the after the photo was captured, a copy of it was already saved to a temporary location(The App's TempState directory) on the local storage.

Windows 8 c# save a camera's picture on local storage

I'm new to C# and I want to create an application metro who can take picture and save themself in localstorage. I know, i need to use isolated storage but i really don't understand how to use it for image. I saw a lot of examples for string but not for picture.
If anyone know how to do it ? Actually i take a picture and i ask the user to record it where he wants. But I want an auto record after the user take the picture. This my code for the moment :
private async void Camera_Clicked(object sender, TappedRoutedEventArgs e)
{
CameraCaptureUI camera = new CameraCaptureUI();
camera.PhotoSettings.CroppedAspectRatio = new Size(16, 9);
StorageFile photo = await camera.
CaptureFileAsync(CameraCaptureUIMode.Photo);
if (photo != null)
{
BitmapImage bmp = new BitmapImage();
IRandomAccessStream stream = await photo.
OpenAsync(FileAccessMode.Read);
bmp.SetSource(stream);
ImageSource.Source = bmp;
ImageSource.Visibility = Visibility.Visible;
appSettings[photoKey] = photo.Path;
FileSavePicker savePicker = new FileSavePicker();
savePicker.FileTypeChoices.Add
("jpeg image", new List<string>() { ".jpeg" });
savePicker.SuggestedFileName = "New picture";
StorageFile ff = await savePicker.PickSaveFileAsync();
if (ff != null)
{
await photo.MoveAndReplaceAsync(ff);
}
}
}
All what you need to do is to replace File Picker logic with retrieving of StorageFile object in Local folder, for example like this:
private async void Camera_Clicked(object sender, TappedRoutedEventArgs e)
{
CameraCaptureUI camera = new CameraCaptureUI();
camera.PhotoSettings.CroppedAspectRatio = new Size(16, 9);
StorageFile photo = await camera.
CaptureFileAsync(CameraCaptureUIMode.Photo);
if (photo != null)
{
var targetFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("some_file_name.jpg");
if (targetFile != null)
{
await photo.MoveAndReplaceAsync(targetFile);
}
}
}

How to Update/replace image in WPF by clicking button

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;

Categories