Image From Music Library Not Showing in UWP app - windows

I'm new to UWP development & I'm just showing image in my app from the Music Library.
Infact, I have added Music Library in the app's "Capabilities" & I can confirm that I have access to Music Library as I can read & write files in it.
But when I try to load a image in XAML, it just does not shows...
<Image Height="200" Width="200" Source="C:/Users/Alex Mercer/Music/Album/albumArt.png" />
Please help me understand & solve the problem.
😃 Thanks a lot!

Although we enable the corresponding capabilities, accessing files through paths is still strictly restricted in UWP.
In fact, it is not a good idea to write the full path in XAML, because you cannot guarantee that the path must exist on the device where the application is installed.
To display the pictures in the music library, you can do this:
xaml
<Image Height="200" Width="200" x:Name="AlbumImage" Loaded="AlbumImage_Loaded"/>
xaml.cs
private async void AlbumImage_Loaded(object sender, RoutedEventArgs e)
{
try
{
var albumFolder = await KnownFolders.MusicLibrary.GetFolderAsync("Album");
var albumPic = await albumFolder.GetFileAsync("albumArt.png");
var bitmap = new BitmapImage();
using (var stream = await albumPic.OpenAsync(FileAccessMode.Read))
{
await bitmap.SetSourceAsync(stream);
}
AlbumImage.Source = bitmap;
}
catch (FileNotFoundException)
{
// File or Folder not found
}
catch (Exception)
{
throw;
}
}

Related

Xamarin Camera Control Photo does not show on device

I used the following example to work with Camera Control in Xamarin
Example used: adamped/CameraXF
Following piece of code works fine in emulator. On device, it takes up the space of an image but image doesn't load. Any leads?
private async void CameraButton_Clicked(object sender, EventArgs e)
{
var photo = await Plugin.Media.CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions() { });
if (photo != null)
PhotoImage.Source = ImageSource.FromStream(() => { return photo.GetStream(); });
}
I would recommend you to use the CachedImage class from FFImageLoading. I have encountered this problem in lower-end devices and using CachedImage fixes it.
Here is the repo : https://github.com/luberda-molinet/FFImageLoading
Docs : https://github.com/luberda-molinet/FFImageLoading/wiki/Xamarin.Forms-API
Here is the xaml sample.
<ffimageloading:CachedImage HorizontalOptions="Center" VerticalOptions="Center"
WidthRequest="300" HeightRequest="300"
DownsampleToViewSize="true"
Source = "http://loremflickr.com/600/600/nature?filename=simple.jpg">
</ffimageloading:CachedImage>
Dont forget to set the DownsampleToViewSize="true".
This should solve your issue.

File Picker window not open in xamarin forms?

on Button click file picker window not open in xamarin forms-
I am using Xam.Plugin.FilePicker
Here is my button event code-
async void FilePickerEvent(object sender, EventArgs e)
{
try
{
FileData filedata = new FileData();
filedata = await CrossFilePicker.Current.PickFile();
byte[] data = filedata.DataArray;
string name = filedata.FileName;
foreach(byte b in filedata.DataArray)
{
string attachment = b.ToString();
}
}
catch (Exception ex)
{
string msg = ex.Message;
}
}
I tried this plugin on Android device and it works well. I installed the plugin in all projects and then added these permissions to AndroidManifest.xml file as it is in the documentation.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Then in my MainPage.xaml I created a button
<Button Text="Open File" Clicked="Button_Clicked" />
And in my MainPage.xaml.cs created event
private async void Button_Clicked(object sender, EventArgs e)
{
var file = await CrossFilePicker.Current.PickFile();
}
I picked the file and retrieve the property FileName and DataArray without any problem.
There is a thread on xamarin forum or there is a issue list on their github.
There is a newer forked github project that received quite some fixes, e.g. for Android picking from download folder, OneDrive or Google Drive storage. The project is here:
https://github.com/jfversluis/FilePicker-Plugin-for-Xamarin-and-Windows
(note: I'm one of the contributors).
You just have to change the NuGet package name to Xamarin.Plugin.FilePicker, the API is the same.

Xamarin: add image to my button from PCL (not from Resources)

I'm working on a Xamarin.Forms project utilizing PCL (not the shared project).
I have a few images in my Resources folders in both Android and iOS project.
This works and the icons show in buttons as they're supposed to:
<Button Image="speaker.png" Grid.Row="0" Grid.Column="0" />
I also have a folder in my PCL project with some images: images/icons/speaker.png
I've tried this:
<Button Image="{local:EmbeddedImage TestThree.images.icons.speaker.png}" />
...but that didn't work...
I would like those buttons to show images from my images folder in my PCL project.
So my question would be...
<Button WHAT GOES HERE? Grid.Row="0" Grid.Column="0" />
When Button.Image wants FileImageStream, I give it to him. But as images in the project I still use embedded resources PNG files in PCL (or .NET standard 2.0) library (project).
For example the PCL project name is "MyProject" and I have an image placed in its subfolder "Images\Icons\ok.png". Then the resource name (e.g. for ImageSource.FromResource) is "MyProject.Images.Icons.ok.png".
This method copies embedded resource file into the file in application local storage (only first time).
public static async Task<string> CopyIcon(string fileName)
{
if (String.IsNullOrEmpty(fileName)) return "";
try
{
// Create (or open if already exists) subfolder "icons" in application local storage
var fld = await FileSystem.Current.LocalStorage.CreateFolderAsync("icons", CreationCollisionOption.OpenIfExists);
if (fld == null) return ""; // Failed to create folder
// Check if the file has not been copied earlier
if (await fld.CheckExistsAsync(fileName) == ExistenceCheckResult.FileExists)
return (await fld.GetFileAsync(fileName))?.Path; // Image copy already exists
// Source assembly and embedded resource path
string imageSrcPath = $"MyProject.Images.Icons.{fileName}"; // Full resource name
var assembly = typeof(FileUtils).GetTypeInfo().Assembly;
// Copy image from resources to the file in application local storage
var file = await fld.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists);
using (var target = await file.OpenAsync(PCLStorage.FileAccess.ReadAndWrite))
using (Stream source = assembly.GetManifestResourceStream(imageSrcPath))
await source.CopyToAsync(target); // Copy file stream
return file.Path; // Result is the path to the new file
}
catch
{
return ""; // No image displayed when error
}
}
When I have a regular file, I can use it for the FileImageStream (Button.Image).
The first option is use it from the code.
public partial class MainPage : ContentPage
{
protected async override void OnAppearing()
{
base.OnAppearing();
btnOk.Image = await FileUtils.CopyIcon("ok.png");
}
}
Also I can use it in the XAML, but I must create an implementation of IMarkupExtension interface.
[ContentProperty("Source")]
public class ImageFileEx : IMarkupExtension
{
public string Source { get; set; }
public object ProvideValue(IServiceProvider serviceProvider)
{
return Task.Run(async () => await FileUtils.CopyIcon(Source)).Result;
}
}
Now I can assign the image direct in the XAML.
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MyProject"
x:Class="MyProject.MainPage"
xmlns:lcl="clr-namespace:MyProject;assembly=MyProject">
<Grid VerticalOptions="Fill" HorizontalOptions="Fill">
<Button Image="{lcl:ImageFileEx Source='ok.png'}" Text="OK" />
</Grid>
</ContentPage>
For this solution the NuGet PCLStorage is needed.
The reason that does not work is because the properties are bound to different types.
Button's Image property takes a "FileImageSource" - Github
Image's Source property takes a "ImageSource" - Github
From the local:EmbeddedImage im guessing you were using the extension from Xamarin forms image docs
That would not work because it loads a "StreamImageSource" instead of "FileImageSource".
In practice you should not do this as it would not load from different dimension images(#2x, xhdpi etc) and would give bad quality images and not support multiple resolutions.
You could use a view container(Stack layout etc) with a TapGestureRecognizer and an image centered inside it or create a custom renderer which really is more effort than its worth. None of these still would still obviously not handle multiple images though.
The correct solution would be to generate the correct size images from the base(Which I would assume would be MDPI Android or 1X for iOS) and put them in the correct folders and reference them in your working Button example.

How to show image files from a directory in a flipview?

I found many samples of displaying images from a resource in a Windows Store app and got it to display images within a sample, but I would require the flipview to show images in a directory, or at least to show image file names I provide by code. With everything I tried so far the flipview remains empty. I maybe missing something obvious, this is the relevant part of the XAML:
<FlipView x:Name="flipView1" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="809,350,9,7" Width="548" Height="411" >
<FlipView.ItemTemplate>
<DataTemplate>
<Image Source="{Binding Path=Image }" Stretch="Uniform"/>
</DataTemplate>
</FlipView.ItemTemplate>
</FlipView>
this works, but it requires me to add the images a resource first....
ImageBrush brush1 = new ImageBrush();
brush1.ImageSource = new BitmapImage(new Uri("ms-appx:///Assets/P1000171.jpg"));
FlipViewItem flipvw1 = new FlipViewItem();
flipvw1.Background = brush1;
flipView1.Items.Add(flipvw1);
but (for example) this doesn't:
string name = String.Format(#"c:\temp\P1000171.JPG");
Uri uri = new Uri(name);
BitmapImage img = new BitmapImage(uri);
flipView1.Items.Add(img);
What do I miss?
In the meantime I've found the answer myself which I now add for future readers. The above example won't work because a Windows 8 app isn't allowed to access most of the PC's directories without the user having selected one using a FolderPicker. The program can re-use that directory later with:
StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFolderToken", folder);
I've changed the above XAML here:
<Image Source="{Binding}" Stretch="UniformToFill"/>
The Task below will show all .JPG files in the Pictures library in a Flipview, if, in the Package.appxmanifest, Capabilities, "Pictures library" has been checked:
public async Task flipviewload()
{
IReadOnlyList<StorageFile> fileList = await picturesFolder.GetFilesAsync();
var images = new List<BitmapImage>();
if (fileList != null)
{
foreach (StorageFile file in fileList)
{
string cExt = file.FileType;
if (cExt.ToUpper()==".JPG")
{
Windows.Storage.Streams.IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
using (Windows.Storage.Streams.IRandomAccessStream filestream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
BitmapImage bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(fileStream);
images.Add(bitmapImage);
}
}
}
}
flpView.ItemsSource = images;
}

System.OutOfMemoryException while reading and binding image from isolated storage

This is the code I am using for binding image in XAML
<Border toolkit:TiltEffect.IsTiltEnabled="true" Height="350" Width="400" Grid.ColumnSpan="3">
<Grid Height="350" Width="400" Margin="70,0,70,0" x:Name="Container1">
<Grid.Background>
<ImageBrush ImageSource="{Binding ImageCollection[0]}" Stretch="Uniform" AlignmentX="Left" AlignmentY="Center"/>
</Grid.Background>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Tap">
<i:InvokeCommandAction Command="{Binding ImageTapCommand}" CommandParameter="CONTAINER0"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Grid>
</Border>
Likewise I am using 4 border for displaying my recent images.
In my ViewModel I am using the below method for reading image from isolated storage.
public Stream GetFileStream(string filename, ImageLocation location)
{
try
{
lock (SyncLock)
{
if (location == ImageLocation.RecentImage)
{
filename = Constants.IsoRecentImage + #"\" + filename;
}
using (var iSf = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!iSf.FileExists(filename)) return null;
var fs = iSf.OpenFile(filename, FileMode.Open, FileAccess.Read);
return fs;
}
}
}
catch (Exception ex)
{
return null;
}
}
And after getting the stream I will use this below written method four building the WritableBitmap for UI binding
private WriteableBitmap BuildImage(Stream imageStream)
{
using (imageStream)
{
var image = new BitmapImage();
image.SetSource(imageStream);
return new WriteableBitmap(image);
}
}
In this case my issue is after navigating to and from my page for two - three times. The app crashes on BuildImage() method where I am using " image.SetSource(imageStream);" method. I tried many alternatives but failed. The exception I am getting is "System.OutOfMemoryException "
I tried Image control instead of Image brush.
I tried Bitmap instead of WritableBitmap etc. but the result is same.
The app crashing rate will reduce if I use small images. But the crash rate is high with the images taken through camera.
I am trying for a solution to this issue for last one week, But didn't find any alternative to fix the issue.
I found a link that talks about similar issue But didn't get many to solve the issue
Try this,
var bitmapImage = new BitmapImage();
bitmapImage.SetSource(stream);
bitmapImage.CreateOptions = BitmapCreateOptions.None;
var bmp = new WriteableBitmap((BitmapSource) bitmapImage);
bitmapImage.UriSource = (Uri) null;
return bmp;
Silverlight caches images by default to improve performance. You should call
image.UriSource = null after using the BitmapImage to dispose of the resources.
Are you reseting/disposing the IsolatedStorageFileStream and the IsolatedStorageFile after you use them?
Have you tried forcing the garbage collector to run to see if that makes any difference.
GC.Collect();
This is not intended as a solution - you should never have to call GC.Collect, but it might help determine whether your problem is a memory leak or just a delay in the memory being reclaimed.

Resources