I'm trying to store a model informations in my Data Base, this informations contain an image, so I created a simple view with some entrys, with a media picker button to pick it and an image witch display the picked one.
This is the button method and the store method:
async void Button_Clicked(System.Object sender, System.EventArgs e)
{
var result = await MediaPicker.PickPhotoAsync(new MediaPickerOptions
{
Title = "Please pick a photo"
});
if (result != null)
{
var stream = await result.OpenReadAsync();
resultImage.Source = ImageSource.FromStream(() => stream);
}
}
public async Task SaveMachine()
{
var machine = new Machine
{
Machine_Name = nom.Text,
Machine_Qr = qr.Text,
Files = resultImage
};
await _rest.AddMachine(machine);
await Shell.Current.GoToAsync("..");
}
But I can't create Files = resultImage because the Files in the model is in IFormFile.
Related
I m trying to load an image classification model made with pytorch into a c# aplication. In order to acomplish this task i use an async task, but when i run the program it throws me a null reference exception because it seams it doesn't load the model.
using System;
using System.Threading.Tasks;
using Windows.AI.MachineLearning;
using Windows.Graphics.Imaging;
using Windows.Media;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace AI_Test1
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
// All the required fields declaration
private Model modelGen;
private Input image = new Input();
private Output results;
private StorageFile selectedStorageFile;
private string label = "";
private float probability = 0;
private Helper helper = new Helper();
public enum Labels
{
Has_Lighter,
Has_No_Lighter,
}
public MainPage()
{
this.InitializeComponent();
_ = loadModel();
}
private async Task loadModel()
{
// Get an access the ONNX model and save it in memory.
StorageFile modelFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri($"ms-appx:///Assets/LTM-Classic_Model.onnx"));
// Instantiate the model.
modelGen = await Model.CreateFromStreamAsync(modelFile);
}
private async void OpenFileButton_Click(object sender, RoutedEventArgs e)
{
if (!await getImage())
{
return;
}
// After the click event happened and an input selected, begin the model execution.
// Bind the model input
await imageBind();
// Model evaluation
await evaluate();
// Extract the results
ExtractResult();
// Display the results
displayResult();
}
private async Task<bool> getImage()
{
try
{
// Trigger file picker to select an image file
FileOpenPicker fileOpenPicker = new FileOpenPicker();
fileOpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
fileOpenPicker.FileTypeFilter.Add(".jpg");
fileOpenPicker.FileTypeFilter.Add(".png");
fileOpenPicker.ViewMode = PickerViewMode.Thumbnail;
selectedStorageFile = await fileOpenPicker.PickSingleFileAsync();
if (selectedStorageFile == null)
{
return false;
}
}
catch (Exception)
{
return false;
}
return true;
}
private async Task imageBind()
{
UIPreviewImage.Source = null;
try
{
SoftwareBitmap softwareBitmap;
using (IRandomAccessStream stream = await selectedStorageFile.OpenAsync(FileAccessMode.Read))
{
// Create the decoder from the stream
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
// Get the SoftwareBitmap representation of the file in BGRA8 format
softwareBitmap = await decoder.GetSoftwareBitmapAsync();
softwareBitmap = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
}
// Display the image
SoftwareBitmapSource imageSource = new SoftwareBitmapSource();
await imageSource.SetBitmapAsync(softwareBitmap);
UIPreviewImage.Source = imageSource;
// Encapsulate the image within a VideoFrame to be bound and evaluated
VideoFrame inputImage = VideoFrame.CreateWithSoftwareBitmap(softwareBitmap);
// Resize the image size to 32x32
inputImage = await helper.CropAndDisplayInputImageAsync(inputImage);
// Bind the model input with image
ImageFeatureValue imageTensor = ImageFeatureValue.CreateFromVideoFrame(inputImage);
image.input = imageTensor;
// Encapsulate the image within a VideoFrame to be bound and evaluated
//VideoFrame inputImage = VideoFrame.CreateWithSoftwareBitmap(softwareBitmap);
// bind the input image
//ImageFeatureValue imageTensor = ImageFeatureValue.CreateFromVideoFrame(inputImage);
//image.modelInput = imageTensor;
}
catch (Exception )
{
}
}
private void ExtractResult()
{
// Retrieve the results of evaluation
var mResult = results.output as TensorFloat;
// convert the result to vector format
var resultVector = mResult.GetAsVectorView();
probability = 0;
int index = 0;
// find the maximum probability
for (int i = 0; i < resultVector.Count; i++)
{
var elementProbability = resultVector[i];
if (elementProbability > probability)
{
index = i;
}
}
label = ((Labels)index).ToString();
}
private void displayResult()
{
displayOutput.Text = label;
}
private async Task evaluate()
{
results = await modelGen.EvaluateAsync(image);
}
}
}
According to what I could understand from your code, the modelGen is not initialized before you have called the evaluate() method. Apparantly, you have created a method loadModel() for this purpose, so I am guessing that you need to call the loadmodel() before you call evaluate().
So edit this portion of the code
private async void OpenFileButton_Click(object sender, RoutedEventArgs e)
{
if (!await getImage())
{
return;
}
// After the click event happened and an input selected, begin the model execution.
// Bind the model input
await imageBind();
await loadModel(); // EDITED: Load Model here
// Model evaluation
await evaluate();
// Extract the results
ExtractResult();
// Display the results
displayResult();
}
I am trying to play a song from my listview in UWP. However when I click on the song (listview item) to play it I get the follwing error:
System.IO.FileNotFoundException: 'The system cannot find the file specified. (Exception from HRESULT: 0x80070002)'
This is my code:
private async Task InitFolderAsync()
{
StorageFolder musicLib = KnownFolders.MusicLibrary;
var files = await musicLib.GetFilesAsync();
foreach (var file in files)
{
StorageItemThumbnail currentThumb = await file.GetThumbnailAsync(ThumbnailMode.MusicView, 50, ThumbnailOptions.UseCurrentScale);
var albumCover = new BitmapImage();
albumCover.SetSource(currentThumb);
var musicProperties = await file.Properties.GetMusicPropertiesAsync();
var musicname = musicProperties.Title;
var musicdur = musicProperties.Duration;
var artist = musicProperties.Artist;
if (artist == "")
{
artist = "Unknown";
}
var album = musicProperties.Album;
if (album == "")
{
album = "Unknown";
}
MusicList.Add(new MusicLib
{
FileName = musicname,
Artist = artist,
Album = album,
Duration = musicdur,
AlbumCover = albumCover,
MusicPath = file.Path
});
}
}
private async void SongClicked(object sender, ItemClickEventArgs e)
{
var file = await KnownFolders.MusicLibrary.GetFileAsync(e.ClickedItem.ToString());
if (file != null)
{
var stream = await file.OpenReadAsync();
mediaElement.SetSource(stream, file.ContentType);
mediaElement.Play();
}
}
private async void objMediaPlayer_MediaEnded(object sender, RoutedEventArgs e)
{
// If the end of the ListView is reached and the last song was played stop.
if ((AudioFilesLV.SelectedIndex + 1) == AudioFilesLV.Items.Count)
{
mediaElement.Stop();
}
else
{
// This line you should try to change. When the last song was not played
//-> select next one and play them.
AudioFilesLV.SelectedIndex = AudioFilesLV.SelectedIndex + 1;
var file = await KnownFolders.MusicLibrary.GetFileAsync(AudioFilesLV.SelectedItem.ToString());
if (file != null)
{
var stream = await file.OpenReadAsync();
mediaElement.SetSource(stream, file.ContentType);
mediaElement.Play();
}
}
}
So basically after you click on the song to play it should then automatically go to the next song and play it. I haven't got to that stage yet as it does not want to play the song I clicked.
Thanks
Try to cast e.ClickedItem to a MusicLib and then pass its MusicPath to the GetFileAsync method:
private async void SongClicked(object sender, ItemClickEventArgs e)
{
var clickedItem = e.ClickedItem as MusicLib;
if (clickedItem != null)
{
var file = await KnownFolders.MusicLibrary.GetFileAsync(clickedItem.MusicPath);
if (file != null)
{
var stream = await file.OpenReadAsync();
mediaElement.SetSource(stream, file.ContentType);
mediaElement.Play();
}
}
}
i am creating mobile application where user can post adverts with pictures and text. I am using Media.Plugin by James Montemagno. That works very well. Also the user should be able to tap on the picture to review and possibly delete. I am not sure how to access these pictures, i dont know where they are stored so even if i would want to delete them i am not sure how to access each picture. COuld you please help me?
The user is able to take several images and then they are displayed on the main page. I would like the user to be able to review them once again and then if he continues with them to the second page he will upload some other data and on the third page it should all display together. How can i Display pictures on the third page?
public partial class AddingPage : ContentPage
{
AdLogEntry adLogEntry = new AdLogEntry();
//CameraService cameraService = new CameraService();
public byte[] imageAsBytes;
public string pathLabel;
private const int MaxColumns = 3;
private int _currentRow = 0;
private int _currentColumn = 0;
public AddingPage()
{
InitializeComponent();
}
protected override async void OnAppearing()
{
base.OnAppearing();
await MainProgressBar.ProgressTo(0, 250, Easing.Linear); ;
}
private async void NextStep_Clicked(object sender, EventArgs e)
{
await Navigation.PushAsync(new Informations());
}
private async void TakePicture_Clicked(object sender, EventArgs e)
{
await TakePicture();
}
private async Task TakePicture()
{
MediaFile file = null;
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
await DisplayAlert("Nemáme přístup", "Nelze nalézt kameru", "OK");
return;
}
var imageSource = await DisplayActionSheet("Foto", "Cancel", null, new string[] { "Pořídit novou fotku", "Nahrát foto z galerie" });
var photoName = Guid.NewGuid().ToString() + ".jpg";
switch (imageSource)
{
case "Pořídit novou fotku":
file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
{
SaveToAlbum = true,
Directory = "Photos",
Name = photoName
});
//Get the public album path
var aPpath = file.AlbumPath;
//Get private path
var path = file.Path;
break;
case "Nahrát foto z galerie":
file = await CrossMedia.Current.PickPhotoAsync();
//Directory.GetFiles( "Photos");
break;
default:
break;
}
if (file == null)
return;
// Photo => Grid
_currentColumn++;
if (_currentColumn > MaxColumns - 0)
{
_currentColumn++;
_currentRow++;
// Add a new row definition by copying the first row.
ImageGridContainer.RowDefinitions.Add(ImageGridContainer.RowDefinitions[0]);
}
var newImage = new Image()
{
Source = ImageSource.FromFile(file.Path),
VerticalOptions = LayoutOptions.FillAndExpand,
HorizontalOptions = LayoutOptions.FillAndExpand,
Aspect = Aspect.AspectFill,
Scale = 0
};
ImageGridContainer.Children.Add(newImage, _currentColumn, _currentRow);
await Task.Delay(250);
await newImage.ScaleTo(1, 250, Easing.SpringOut);
}
I have been following this tutorial http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj681698%28v=vs.105%29.aspx.
So far is what I was searching for, but the only problem is that when i close and open the app again the file and the text is not saved anymore, so I want to the file be saved forever with the text.
I want to it be saved here http://gyazo.com/82e838cd2385cea7021647a8d39f49a8.png/level/batlevel.txt. So when I can open the app again the text that was write there it will be there
private async void btnWrite_Click(object sender, RoutedEventArgs e)
{
await WriteToFile();
// Update UI.
this.btnWrite.IsEnabled = false;
this.btnRead.IsEnabled = true;
}
private async Task WriteToFile()
{
// Get the text data from the textbox.
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(this.textBox1.Text.ToCharArray());
// Get the local folder.
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
// Create a new folder name DataFolder.
var dataFolder = await local.CreateFolderAsync("level",
CreationCollisionOption.OpenIfExists);
// Create a new file named DataFile.txt.
var file = await dataFolder.CreateFileAsync("level.txt",
CreationCollisionOption.ReplaceExisting);
// Write the data from the textbox.
using (var s = await file.OpenStreamForWriteAsync())
{
s.Write(fileBytes, 0, fileBytes.Length);
}
}
private async void btnRead_Click(object sender, RoutedEventArgs e)
{
await ReadFile();
// Update UI.
this.btnWrite.IsEnabled = true;
this.btnRead.IsEnabled = false;
}
private async Task ReadFile()
{
// Get the local folder.
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
if (local != null)
{
// Get the DataFolder folder.
var dataFolder = await local.GetFolderAsync("level");
// Get the file.
var file = await dataFolder.OpenStreamForReadAsync("level.txt");
// Read the data.
using (StreamReader streamReader = new StreamReader(file))
{
this.textBlock1.Text = streamReader.ReadToEnd();
}
}
}
}
}
I believe you should be opening your level.txt file with the OpenIfExists option instead of ReplaceExisting :
// Create a new file named DataFile.txt.
var file = await dataFolder.CreateFileAsync( "level.txt", CreationCollisionOption.OpenIfExists );
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);
}
}
}