Bind images to listbox with datatemplate from app package folder - c#

Hi I need bind images to listbox but when I try it I get FILE NOT FOUND but file is stored in application package in folder layoutGraphics. I try put files to default folder but I get same result anyone know what is bad?
var file = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("ms-appx:///layoutGraphics/offline.png");
var fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
var img = new BitmapImage();
img.SetSource(fileStream);
ImgSource = img;
// property
private BitmapImage _imgSource;
public BitmapImage ImgSource
{
get { return _imgSource; }
set
{
_imgSource = value;
OnPropertyChanged("MyDatasMessagesUserList");
}
}
Or anyone know better solution how I can bind imagess from app folder to my listbox with datatemplate?

Windows.Storage.ApplicationData.Current.LocalFolder is retriving file from the application storage not the package. For the package folder you need to use Windows.ApplicationModel.Package.Current.InstalledLocation. Also the GetFileAsync take just the name of a file not a full path.
Here is the code to acomplish what you want:
var layoutGraphiceFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("layoutGraphics")
var file=await layoutGraphiceFolder.GetFileAsync("offline.png");
Another way to do it with the full path is:
var file=await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///layoutGraphics/offline.png"));

Related

Xamarin.Essentials Share drawable

I'm trying to share a local image loacted in my Resources/Drawables folder in Android.
I'm using Xamarin and the Xamarin.Essentials plugin.
So there is this function:
await Share.RequestAsync(new ShareFileRequest
{
Title = Title,
File = new ShareFile(file)
});
So for the File I need the Path to the File from the Drawable Folder.
I have tried so much variations.
For example:
var file = Android.Net.Uri.Parse("android.resource://" + Android.App.Application.Context.PackageName + "/" + Resource.Drawable.image).Path;
But I always get an error, that the file is not found.
What I'm doing wrong?
Thanks in advance
Because Resources don't have file paths, as #Jason said I saved the image in another accesible file.
So I don't know if this is the best solution, but it works for me:
Drawable drawable = ResourcesCompat.GetDrawable(Resources, Resource.Drawable.image, null);
Bitmap bitmap = ((BitmapDrawable)drawable).Bitmap;
byte[] imgByteArray;
using (var stream = new MemoryStream())
{
bitmap.Compress(Bitmap.CompressFormat.Png, 0, stream);
imgByteArray = stream.ToArray();
}
var file = System.IO.Path.Combine(FileSystem.CacheDirectory, "share.png");
File.WriteAllBytes(file, imgByteArray);
await Share.RequestAsync(new ShareFileRequest
{
Title = "Share",
File = new ShareFile(file)
});

Xamarin Forms Load image from folder inside project

I have a problem. I am trying to save an Image to a folder in my project (not the Resources folder!) and load theimage from that folder into an Image holder as source. I want the image to be saved in a folder called: TempImages and my app name is MyApp. Here is the code I have now:
Saving:
using (var image = args.Surface.Snapshot())
using (var data = image.Encode(SKEncodedImageFormat.Png, 80))
using (var stream = File.OpenWrite(Path.Combine("MyApp.TempImages", "CreatedImage.png")))
{
data.SaveTo(stream);
}
Opening:
string resourceID = string.Format("MyApp.TempImages.CreatedImage.png");
Assembly assembly = GetType().GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream(resourceID);
imgCanvas.Source = ImageSource.FromFile(resourceID);
But I think that File.OpenWrite a local file on my pc means, but I am not sure. And therefore I am not sure if I am opening the file correctly. Now I get the error that the save path doesn't exist.
How can I fix this?
you should be able to create any folder structure you want within one of the app writeable paths
var path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
var folder = Path.Combine(path,"MySpecialFolder");
Directory.CreateDirectory(folder);
var file = Path.Combine(folder,"MyImage.png");
File.WriteAllBytes(file,data);
var image = File.ReadAllBytes(file);

UWP image picker not working for image source

I'm trying to get image picker to work, and it does, but for some reason it won't populate as an image.
var openPicker = new FileOpenPicker
{
ViewMode = PickerViewMode.Thumbnail,
SuggestedStartLocation = PickerLocationId.PicturesLibrary
};
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");
var file = await openPicker.PickSingleFileAsync();
if (file != null)
{
//Image img = new Image();
userImage.Source = new BitmapImage(new Uri(file.Path));
//await ProcessFile(file);
}
and the image is just simply:
<image name="userImage" height="500px" width="500px"/>
This isn't work because the UWP applications have permissions only for some users folders and even you need to browse their files, you need to specify it in the package.manifest of your application which folders you want to access. For simplification, you could create a copy of the file inside the application data folder and get the path from there or set the image source from the stream of the file, but be careful, the second option maybe lead some high memory usage and leaks. You can find how to avoid this here.
You can set stream as source instead of path.
var result = new BitmapImage();
using (var randomAccessStream = await file.OpenAsync(FileAccessMode.Read))
{
await result.SetSourceAsync(randomAccessStream);
}

FilePicker return name and path as strings

I've got a file Save and file open picker that im now trying to integrate the ability to save the Path and FileName as public variable that will be used across the whole project through different methods etc.
I've currently got a SaveFileClass and OpenFileClass.
I've seen examples of using the OpenFileDialog to return the save directory although I don't believe these are suitable for what im after. Maybe in some shape or form but dont seem to make much sense for the FileOpenPicker and FileSavePicker I have in use currently.
What I have currently (minus the returning directories) is this:
public async Task<IStorageFile> OpenFileAsync()
{
FileOpenPicker openPicker = new FileOpenPicker
{
ViewMode = PickerViewMode.List,
SuggestedStartLocation = PickerLocationId.DocumentsLibrary
};
openPicker.FileTypeFilter.Add(".txt");
openPicker.FileTypeFilter.Add(".csv");
return await openPicker.PickSingleFileAsync();
}
This passes back to the MainPage.
Within here, i would like to have a variable to store the selected file path and the selected file name as a string. These will then be used around the project when it comes to quick saving/auto saving and when building my class to load files.
Im just after whether or not FilePicker has this functionality because my understanding of the documentation is a little limited when trying to integrate it with my scenario.
Your OpenFileAsync method returns a selected IStorageFile and this one has a Name property that gets you the name of the file including the file name extension and a Path property that gets you the full file-system path of the file. You can do whatever you want with these values:
private async void OpenFile_Click(object sender, RoutedEventArgs e)
{
OpenFileClass instance = new OpenFileClass();
IStorageFile file = await instance.OpenFileAsync();
if (file != null)
{
string fileName = file.Name;
string filePath = file.Path;
}
}

Path to an embedded resource file

I have an icon in my resource file , which I want to reference.
This is the code that needs that path to an icon file:
IWshRuntimeLibrary.IWshShortcut MyShortcut ;
MyShortcut = (IWshRuntimeLibrary.IWshShortcut)WshShell.CreateShortcut(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + #"\PerfectUpload.lnk");
MyShortcut.IconLocation = //path to icons path . Works if set to #"c:/icon.ico"
Instead of having an external icon file I want it to find an embedded icon file.
Something like
MyShortcut.IconLocation = Path.GetFullPath(global::perfectupload.Properties.Resources.finish_perfect1.ToString()) ;
is this possible ? if so how ?
Thanks
I think this should work, but I can't remember exactly (not at work to double check).
MyShortcut.IconLocation = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("YourNamespace.IconFilename.ico");
Just expanding on SharpUrBrain's answer, which didn't work for me, instead of:
if (null != stream)
{
//Fetch image from stream.
MyShortcut.IconLocation = System.Drawing.Image.FromStream(stream);
}
It should be something like:
if (null != stream)
{
string temp = Path.GetTempFileName();
System.Drawing.Image.FromStream(stream).Save(temp);
shortcut.IconLocation = temp;
}
I think it will help you in some what...
//Get the assembly.
System.Reflection.Assembly CurrAssembly = System.Reflection.Assembly.LoadFrom(System.Windows.Forms.Application.ExecutablePath);
//Gets the image from Images Folder.
System.IO.Stream stream = CurrAssembly.GetManifestResourceStream("ImageURL");
if (null != stream)
{
//Fetch image from stream.
MyShortcut.IconLocation = System.Drawing.Image.FromStream(stream);
}
The res protocol may be able to help you with this: http://msdn.microsoft.com/en-us/library/aa767740(v=vs.85).aspx
In WPF I have done this before:
Uri TweetyUri = new Uri(#"/Resources/MyIco.ico", UriKind.Relative);
System.IO.Stream IconStream = Application.GetResourceStream(TweetyUri).Stream;
NotifyIcon.Icon = new System.Drawing.Icon(IconStream);
The resource it is embedded, so incapsulated in a DLL assembly. So you cannot get its real path, you have to change your approach.
You would probably want to load the resource in memory and write it down to a temp file, then link it from there. Once the icon is is changed on the destination file, you can delete the icon file itself.

Categories

Resources