A similar question got asked here, but I also would like to know if there is a way to limit this filePicker to 4 images or would I have to implement this by my own?
Thank You
It's not pretty but it works for now.
I've declared two global variables of the type ObservableCollection called myimageList and alt-myImageList. I've just check the size of these collections and proceed from this point on.
That's the code:
private async void viewActivated(CoreApplicationView sender, IActivatedEventArgs args1)
{
FileOpenPickerContinuationEventArgs args = args1 as FileOpenPickerContinuationEventArgs;
if (args != null)
{
if (args.Files.Count == 0) return;
view.Activated -= viewActivated;
foreach (var item in args.Files)
{
// instead of item args.Files[0];
StorageFile storageFile = item;
var stream = await storageFile.OpenAsync(FileAccessMode.Read);
var bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(stream);
var wbImage = new WriteableBitmap(bitmapImage.PixelWidth, bitmapImage.PixelHeight);
wbImage.SetSource(stream);
//var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);
//bitmapImage.UriSource = new Uri(item.Path, UriKind.Absolute);
if (myImageList.Count < 4)
{
myImageList.Add(bitmapImage);
alt_myImageList.Add(item);
ErrorMessage.Text = "";
}
else
{
ErrorMessage.Text = "Please pick not more than 4 pictures";
}
}
}
Related
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.
I have a problem while reading a file in C#. Here's the code:
protected override void OnNavigatedTo(NavigationEventArgs EvArgs)
{
base.OnNavigatedTo(EvArgs);
var Args = EvArgs.Parameter as Windows.ApplicationModel.Activation.IActivatedEventArgs;
var FArgs = Args as Windows.ApplicationModel.Activation.FileActivatedEventArgs;
if (Args != null)
{
if (Args.Kind == Windows.ApplicationModel.Activation.ActivationKind.File)
{
var IMG = new Image();
IMG.Loaded += IMG_Loaded;
string FP = FArgs.Files[0].Path;
Uri = FP;
IMG.Source = new BitmapImage(new Uri(FP, UriKind.RelativeOrAbsolute));
FV.Items.Add(IMG);
PathBlock.Text = FArgs.Files[0].Name + " - Image Viewer";
void IMG_Loaded(object sender, RoutedEventArgs e)
{
IMG.Source = new BitmapImage(new Uri(Uri));
}
}
}
if (Args == null)
{
PathBlock.Text = "Image Viewer";
}
}
The problem is at this part:
IMG.Source = new BitmapImage(new Uri(FP, UriKind.RelativeOrAbsolute));
The image won't load, even after trying a resource that the app CAN access in its own files:
IMG.Source = new BitmapImage(new Uri("ms-appx:///09.png, UriKind.RelativeOrAbsolute));
It still won't work.
This only works with this code:
var FOP = new Windows.Storage.Pickers.FileOpenPicker();
StorageFile F = await FOP.PickSingleFileAsync();
IRandomAccessStream FS = await F.OpenAsync(FileAccessMode.Read);
var BI = new BitmapImage();
var IMG = new Image();
await BI.SetSourceAsync(FS);
IMG.Source = BI;
Sadly, I can't use a file stream OR a file picker in the first code example, so I can't make it work as I did here.
Image.Source = new BitmapImage(); doesn't work in UWP
The problem is file Path property does not use to set image source directly in UWP platform.
Derive from your code, it looks you open the image file with current app, if you can get the IStorageItem from FArgs.Files list, you could also convert it as StorageFile, and then pass the opened file stream to BitmapImage.
For more detail steps please refer to the following code.
protected async override void OnNavigatedTo(NavigationEventArgs EvArgs)
{
base.OnNavigatedTo(EvArgs);
var Args = EvArgs.Parameter as Windows.ApplicationModel.Activation.IActivatedEventArgs;
var FArgs = Args as Windows.ApplicationModel.Activation.FileActivatedEventArgs;
if (Args != null)
{
if (Args.Kind == Windows.ApplicationModel.Activation.ActivationKind.File)
{
var IMG = new Image();
string FP = FArgs.Files[0].Path;
var Uri = FP;
StorageFile imageFile = FArgs.Files[0] as StorageFile;
using (var stream = await imageFile.OpenReadAsync())
{
var bitmp = new BitmapImage();
bitmp.SetSource(stream);
IMG.Loaded += (s, e) => { IMG.Source = bitmp; };
}
RootLayout.Children.Add(IMG);
}
}
if (Args == null)
{
}
}
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();
}
}
}
private void Gallery_Click(object sender, object e)
{
view = CoreApplication.GetCurrentView();
var filePicker = new FileOpenPicker
{
SuggestedStartLocation = PickerLocationId.PicturesLibrary,
ViewMode = PickerViewMode.Thumbnail
};
// Filter to include a sample subset of file types
filePicker.FileTypeFilter.Clear();
filePicker.FileTypeFilter.Add(".bmp");
filePicker.FileTypeFilter.Add(".png");
filePicker.FileTypeFilter.Add(".jpeg");
filePicker.FileTypeFilter.Add(".jpg");
mediaCapture.StopPreviewAsync();
filePicker.PickSingleFileAndContinue();
view.Activated += ViewActivated;
}
private async void ViewActivated(CoreApplicationView sender, IActivatedEventArgs args)
{
var arguments = args as FileOpenPickerContinuationEventArgs;
if (arguments != null && arguments.Files.Count != 0)
{
view.Activated -= ViewActivated;
var storageFile = arguments.Files[0];
var file =
await
ApplicationData.Current.LocalFolder.CreateFileAsync("Photo.jpg",
CreationCollisionOption.GenerateUniqueName);
await storageFile.CopyAndReplaceAsync(file);
var bmpImage = new BitmapImage(new Uri(file.Path));
UseThePhoto(bmpImage);
}
else
await mediaCapture.StartPreviewAsync();
}
I have this code above. When I choose an image from a gallery I can use it in an Image control that is on the same page. However, if I want to navigate to any other page, I get an error. No details from it. The code ends in App.g.i.cs
Problem solved. I was using not the blank page template but the basic page. And for some reason the method OnNavigatedFrom invoked this error so i created an override and let it empty, so it couldn't call the navigation helper class.
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);
}
}
}