I m make a simple window phone 8.1 app i want to get aLl photos to display in app and then user select PickMultipleFilesAndContinue ..... but im dont know how to do it . i made this code openfiler picker taking me to phone library ..... Is there any other way to get photos in windows phone 8.1 ?
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");
openPicker.PickMultipleFilesAndContinue();
view.Activated += view_Activated;
}
private async void view_Activated(CoreApplicationView sender, Windows.ApplicationModel.Activation.IActivatedEventArgs args1)
{
FileOpenPickerContinuationEventArgs args = args1 as FileOpenPickerContinuationEventArgs;
bitmapImages = new ObservableCollection<BitmapImage>();
IReadOnlyList<StorageFile> files = args.Files;
if (files.Count > 0)
{
StringBuilder output = new StringBuilder("Picked files:\n");
// Application now has read/write access to the picked file(s)
foreach (StorageFile file in files)
{
output.Append(file.Name + "\n");
using (var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
try
{
BitmapImage bitmapImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
bitmapImage.DecodePixelHeight = 200;
bitmapImage.SetSource(stream);
bitmapImages.Add(bitmapImage);
}
catch (ArgumentException Ex)
{
Debug.WriteLine("Exception ", Ex.Message);
}
}
}
ImageCollection.ItemsSource = bitmapImages;
OutputTextBlock.Text = output.ToString();
}
else
{
OutputTextBlock.Text = "Operation cancelled.";
}
}
by this im geting only selected photos . i want all to display and then user select from them .....
You can access the photos programmatically and then add them to your ImageCollection. I've resized the photos, because otherwise the App crashes on my phone.
StorageFolder pictureFolder = KnownFolders.PicturesLibrary; //or another folder
IReadOnlyList<IStorageItem> nameList = await pictureFolder.GetItemsAsync();
var bitmapImages = new ObservableCollection<BitmapImage>();
foreach (var item in nameList)
{
if (item is StorageFile)
{
if (item.Name.Substring(item.Name.Length - 4, 3).ToLower() == "jpeg" || item.Name.Substring(item.Name.Length - 3, 3).ToLower() == "jpg" || item.Name.Substring(item.Name.Length - 3, 3).ToLower() == "png")
{
Image image = new Image();
StorageFile file = await pictureFolder.GetFileAsync(item.Name);
IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(fileStream);
if (bitmapImage.DecodePixelHeight >= bitmapImage.DecodePixelWidth)
{
bitmapImage.DecodePixelWidth = bitmapImage.DecodePixelHeight / 100;
bitmapImage.DecodePixelHeight = 100;
}
else
{
bitmapImage.DecodePixelHeight = bitmapImage.DecodePixelWidth / 100;
bitmapImage.DecodePixelWidth = 100;
}
bitmapImages.Add(bitmapImage);
}
}
}
Related
I'm trying to get images with Xamarin forms Android and I don't know how to do it.
I have a list called listNameImg (I have the name of the each image there). So, what i want is search each image and then save it in a MultipartFormDataContent
This is my code:
MultipartFormDataContent content3 = new MultipartFormDataContent();
private async void takePhotos()
{
try
{
var file2 = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
{
SaveToAlbum = true
});
while (file2 != null)
{
Image im = new Image();
im.ClassId = contador.ToString();
im.Source = ImageSource.FromFile(file2.Path);
im.HeightRequest = 600;
im.WidthRequest = 600;
im.MinimumHeightRequest = 600;
im.MinimumWidthRequest = 600;
im.VerticalOptions = LayoutOptions.End;
im.HorizontalOptions = LayoutOptions.End;
im.Aspect = Aspect.AspectFill;
imgs.Children.Add(im);
Button deleteButton = new Button();
deleteButton.ClassId = contador.ToString();
deleteButton.Text = "Borrar imagen";
deleteButton.VerticalOptions = LayoutOptions.CenterAndExpand;
deleteButton.HorizontalOptions = LayoutOptions.Center;
deleteButton.MinimumWidthRequest = 100;
deleteButton.ClassId = contador.ToString();
deleteButton.AutomationId = contador.ToString();
deleteButton.Clicked += async (sender, args) => {
listDelete.Add(Convert.ToInt32(deleteButton.ClassId));
imgs.Children.Remove(im);
imgs.Children.Remove(deleteButton);
};
imgs.Children.Add(deleteButton);
listImgName.Add(file2.OriginalFilename);
file2 = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
{
SaveToAlbum = true
});
contador++;
}
btnScannerQR.IsVisible = false;
btnSacarFotos.IsVisible = true;
btnEnviarImagenes.IsVisible = true;
}
catch(Exception ex)
{
await DisplayAlert("Error", "Sorry we had a problem. Try again.", "OK");
await Shell.Current.GoToAsync($"//{nameof(HomePage)}");
}
private async void storageNameInList() {
string testPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "listNameImg.txt");
if (File.Exists(testPath) == false)
{
File.Create(testPath);
}
TextWriter tw = new StreamWriter(testPath);
foreach (var s in listImgName)
{
tw.WriteLine(s);
}
tw.Close();
}
what I'm trying:
private async void sendImages(){
string testPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "listNameImg.txt");
var imgGroup = Directory.GetFiles(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyPictures));
TextReader tw = new StreamReader(testPath);
String line;
int cont = 0;
while ((line = tw.ReadLine()) != null)
{
byte[] byteArray = Encoding.UTF8.GetBytes(line);
content3.Add(new StreamContent(File.OpenRead(line)), "file", line);
cont++;
}
}
My problems are:
how can I write in the file .txt correctly?
how can I get the images and save it in the MultipartFormDataContent?
Thank you very much!
I'm working on an Xamarin Forms application and I have added some code to select multiple images from the phone gallery, I then need to send all selected images to file steam.
Selecting multiple images from the gallery is working fine, but only the last selected image is being sent.
Below is my code
private async Task OnGetExistingPhotoAsync() {
try {
// Selecting multiple images with the MediaGallery plugin
var results = await MediaGallery.PickAsync(3, MediaFileType.Image);
var parameter = new NavigationParameters();
if (results?.Files == null) {
return;
}
foreach(var photo in results.Files) {
if (photo == null) {
PhotoPath = null;
return;
}
string newFile = Path.Combine(FileSystem.CacheDirectory, photo.NameWithoutExtension);
using(var stream = await photo.OpenReadAsync())
using(var newStream = File.OpenWrite(newFile))
await stream.CopyToAsync(newStream);
PhotoPath = newFile;
// This here is only sending the PATH of the last selected image from the gallery
parameter.Add("PhotoPath", PhotoPath);
// In my attempt here, I tried to add each image PATH to a list Array
// But this is not working!
/*
List<string> imageFiles = new List<string>();
imageFiles.Add(Path.Combine(FileSystem.CacheDirectory, photo.NameWithoutExtension));
String[] newFile = imageFiles.ToArray();
using (var stream = await photo.OpenReadAsync())
using (var newStream = File.OpenWrite(newFile)) // This here says that it cannot convert ( string[] to string )
await stream.CopyToAsync(newStream);
parameter.Add("PhotoPath", PhotoPath);
*/
}
//OUTPUT : The PATH is : /data/user/0/se.company.trret.cyn/cache/IMG_20220307_005342
Console.WriteLine("The PATH is : " + PhotoPath);
await _navigationService.GoBackAsync(parameter);
} catch (FeatureNotSupportedException fnsEx) {
await App.Current.MainPage.DisplayAlert("Ett fel inträffade", "Den här funktionen stöds inte av din enhet.", "Ok");
} catch (PermissionException pEx) {
await App.Current.MainPage.DisplayAlert("Ett fel inträffade", "Cykelstaden saknar rättigheter för att läsa dina filer.", "Ok");
} catch (Exception e) {
await App.Current.MainPage.DisplayAlert("Ett fel inträffade", "Ett oväntat fel inträffade. Var god försök igen.", "Ok");
Crashes.TrackError(e);
}
}
I'm trying to play video with AvPlayer in Xamarin.iOS. I'm working with Firebase Storage. If I upload video from android, media type is set as mp4 but from iOS, media type is set as urlencoded. I can play mp4 files with AvPlayer but urlencoded files are not playable. On the other hand, urlencoded files are playable in android VideoView. Do you have any idea about it?
Here my codes, first pick video from gallery:
private async void PickVideoButton_TouchUpInside(object sender, EventArgs e)
{
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsPickVideoSupported)
{
return;
}
try
{
file = await CrossMedia.Current.PickVideoAsync();
if (file == null)
{
return;
}
fileStream = await ConvertMovToMp4();
mediaType = "Video";
avp = new AVPlayer(NSUrl.FromFilename(file.Path));
avpvc = new AVPlayerViewController();
avpvc.Player = avp;
AddChildViewController(avpvc);
GeneralPostingStoryViewBackground.AddSubview(avpvc.View);
avpvc.View.Frame = GeneralPostingStoryImageView.Frame;
avpvc.ShowsPlaybackControls = true;
avp.Play();
}
catch (Exception ex)
{
alert = UIAlertController.Create("Error", "Gallery doesn't support", UIAlertControllerStyle.Alert);
alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
PresentViewController(alert, true, null);
}
}
public async Task<Stream> ConvertMovToMp4()
{
string exportPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string exportFilePath = Path.Combine(exportPath, DateTime.Now.ToString() + ".mp4");
var asset = AVAsset.FromUrl(NSUrl.FromFilename(file.Path));
var length = asset.Duration.Seconds;
lengthDuration = Convert.ToInt32(length).ToString();
AVAssetExportSession export = new AVAssetExportSession(asset, AVAssetExportSession.PresetMediumQuality);
export.OutputUrl = NSUrl.FromFilename(exportFilePath);
export.OutputFileType = AVFileType.Mpeg4;
export.ShouldOptimizeForNetworkUse = true;
await export.ExportTaskAsync();
var stream = File.OpenRead(exportFilePath);
return stream;
}
Then, upload video to firebase storage:
private async void ShareButton_TouchUpInside(object sender, EventArgs e)
{
try
{
var result = await PortableSharediOS(ID, mediaType, fileStream, commentText);
if (result == "Success.")
{
CommonValues.viewControllerIndexList.RemoveAt(CommonValues.viewControllerIndexList.Count - 1);
NavigateViewController();
}
else
{
alert = UIAlertController.Create("Error", result.ToString(), UIAlertControllerStyle.Alert);
alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
PresentViewController(alert, true, null);
}
}
catch (Exception ex)
{
alert = UIAlertController.Create("Error", "Check your internet connection.", UIAlertControllerStyle.Alert);
alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
PresentViewController(alert, true, null);
}
}
Finally, I'm trying to play videos, as I said the mp4 files are playable which I've upload from android, but files which I've upload from iOS, avplayer doesn't play them..:
public async Task GetStory(int storyIndex)
{
var mediaType = stories[storyIndex].StoryType;
var story = stories[storyIndex];
user = await firebaseHelper.GetUser(story.StoryOwner);
if (mediaType == "Photo")
{
GetImage(story.MediaLink, storyViewStoryImageView);
GetImage(user.PhotoLink, storyViewImageView);
storyViewUserName.Text = user.UserName;
storyViewContentView.Text = story.Content;
time = story.MediaDuration;
storyViewDuration.Text = time.ToString();
}
else
{
storyViewUserName.Text = user.UserName;
storyViewContentView.Text = story.Content;
time = story.MediaDuration;
var asset = AVAsset.FromUrl(NSUrl.FromString(story.MediaLink));
var item = AVPlayerItem.FromAsset(asset);
avp = new AVPlayer(item);
avp.Muted = false;
avpvc = new AVPlayerViewController();
avpvc.Player = avp;
AddChildViewController(avpvc);
storyViewStoryImageView.AddSubview(avpvc.View);
avpvc.View.Hidden = false;
avpvc.View.Frame = storyViewStoryImageView.Frame;
avpvc.ShowsPlaybackControls = false;
avp.Play();
storyViewDuration.Text = time.ToString();
}
timer.Enabled = false;
timer.Close();
TimerTextVoid();
}
I can play all files on Android. Doesn't matter where they were uploaded from.
I figured out my problem. Download and save file to device from Firebase Storage. Then assign it to AVAsset. Codes:
public async Task GetStory(int storyIndex)
{
var mediaType = stories[storyIndex].StoryType;
var story = stories[storyIndex];
user = await firebaseHelper.GetUser(story.StoryOwner);
if (mediaType == "Photo")
{
GetImage(story.MediaLink, storyViewStoryImageView);
GetImage(user.PhotoLink, storyViewImageView);
storyViewUserName.Text = user.UserName;
storyViewContentView.Text = story.Content;
time = story.MediaDuration;
storyViewDuration.Text = time.ToString();
}
else
{
storyViewUserName.Text = user.UserName;
storyViewContentView.Text = story.Content;
time = story.MediaDuration;
var asset = await GetVideo(story.MediaLink);
var item = new AVPlayerItem(asset);
avp = new AVPlayer(item);
avp.Muted = false;
avpvc = new AVPlayerViewController();
avpvc.Player = avp;
AddChildViewController(avpvc);
storyViewStoryImageView.AddSubview(avpvc.View);
avpvc.View.Hidden = false;
avpvc.View.Frame = storyViewStoryImageView.Frame;
avpvc.ShowsPlaybackControls = false;
avp.Play();
storyViewDuration.Text = time.ToString();
}
timer.Enabled = false;
timer.Close();
TimerTextVoid();
}
public async Task<AVAsset> GetVideo(string url)
{
string videoFile;
using (var client = new WebClient())
{
var content = client.DownloadData(url);
var stream = new MemoryStream(content);
string folder = Path.GetTempPath();
videoFile = Path.Combine(folder, DateTime.Now.ToString() + ".mp4");
if (!System.IO.File.Exists(videoFile))
{
using (FileStream outputStream = System.IO.File.Create(videoFile))
{
await stream.CopyToAsync(outputStream);
}
}
}
var asset = AVUrlAsset.FromUrl(NSUrl.FromFilename(videoFile));
return asset;
}
I have folders and files on the "koleksibuku" folder on carousel. I want to be when moveBtn clicked, it will display a list of names of available folders (including root folder). How do I display a list of available folders in the "koleksibuku" folder?
Code to display files and folders on gridview:
loading.IsIndeterminate = true;
StorageFolder koleksibuku = await installedLocation.CreateFolderAsync("koleksibuku", CreationCollisionOption.OpenIfExists);
ObservableCollection<Book> datasource = new ObservableCollection<Book>();
IReadOnlyList<StorageFile> files = await koleksibuku.GetFilesAsync();
IReadOnlyList<StorageFolder> folders = await koleksibuku.GetFoldersAsync();
StorageFolder thumbfolder = await installedLocation.CreateFolderAsync("thumb", CreationCollisionOption.OpenIfExists);
files = await koleksibuku.GetFilesAsync();
folders = await koleksibuku.GetFoldersAsync();
foreach (StorageFile file in files)
{
Book buku = new Book();
buku.Name = file.DisplayName.ToString();
if ((isbukudownloading(file.Name.ToString())) && (file.Name.ToString() != DownloadFileName))
{
}
else
{
StorageFile thumbFile;
StorageFolder thumbFolder;
bool bukuada = true;
try
{
var folder1 = await installedLocation.GetFolderAsync("kolesibuku");
thumbFile = await thumbfolder.GetFileAsync(file.Name.ToString() + ".png");
BitmapImage bi = new BitmapImage();
bi.SetSource(await thumbFile.OpenAsync(FileAccessMode.Read));
buku.Image = bi;
datasource.Add(buku);
}
catch
{
bukuada = false;
}
if (!bukuada)
{
loading.IsIndeterminate = true;
var task = Task.Run(async () => { await RenderCoverBuku(file.Name.ToString(), 0); });
task.Wait();
thumbFile = await thumbfolder.GetFileAsync(file.Name.ToString() + ".png");
BitmapImage bi = new BitmapImage();
bi.SetSource(await thumbFile.OpenAsync(FileAccessMode.Read));
buku.Image = bi;
datasource.Add(buku);
}
}
}
foreach (StorageFolder folder in folders)
{
Book buku = new Book();
buku.Name = folder.DisplayName.ToString();
BitmapImage folderImage = new BitmapImage(new Uri("ms-appx:///images/folders_png8761.png"));
buku.Image = folderImage;
datasource.Add(buku);
}
this.carousel.ItemsSource = datasource;
this.carousel.SelectedItem = carousel.Items[0];
loading.IsIndeterminate = false;
}
private void moveBtn_Click(object sender, RoutedEventArgs e)
{
}
Note:
The name of the folder created by the user as desired user
I want to trim a music file(mp3) in my UWP win 10 app. I try using Naudio but it's not working in my app, so how can i do it ?
Anyone any ideas?
If you want to trim a mp3 file, you can use Windows.Media.Editing namespace, especially MediaClip class.
By default, this class is used for clipping from a video file. But we can also use this class to trim mp3 file by setting MediaEncodingProfile in MediaComposition.RenderToFileAsync method while rendering.
Following is a simple sample:
var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
openPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.MusicLibrary;
openPicker.FileTypeFilter.Add(".mp3");
var pickedFile = await openPicker.PickSingleFileAsync();
if (pickedFile != null)
{
//Created encoding profile based on the picked file
var encodingProfile = await MediaEncodingProfile.CreateFromFileAsync(pickedFile);
var clip = await MediaClip.CreateFromFileAsync(pickedFile);
// Trim the front and back 25% from the clip
clip.TrimTimeFromStart = new TimeSpan((long)(clip.OriginalDuration.Ticks * 0.25));
clip.TrimTimeFromEnd = new TimeSpan((long)(clip.OriginalDuration.Ticks * 0.25));
var composition = new MediaComposition();
composition.Clips.Add(clip);
var savePicker = new Windows.Storage.Pickers.FileSavePicker();
savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.MusicLibrary;
savePicker.FileTypeChoices.Add("MP3 files", new List<string>() { ".mp3" });
savePicker.SuggestedFileName = "TrimmedClip.mp3";
StorageFile file = await savePicker.PickSaveFileAsync();
if (file != null)
{
//Save to file using original encoding profile
var result = await composition.RenderToFileAsync(file, MediaTrimmingPreference.Precise, encodingProfile);
if (result != Windows.Media.Transcoding.TranscodeFailureReason.None)
{
System.Diagnostics.Debug.WriteLine("Saving was unsuccessful");
}
else
{
System.Diagnostics.Debug.WriteLine("Trimmed clip saved to file");
}
}
}