Xamarin - CachedImage - Access the downloaded file - xamarin.forms

I am using the CachedImage component of ffimageloading. I have a kind of gallery with a carousel view.
All the images are loaded through an internet URL, they are not local images. I would like to add the image sharing function. But I don't want to download the file again, I would like to know if there is a way to access the file that the CachedImage component already downloaded to be able to reuse it in the share function.

try using MD5Helper
var path = ImageService.Instance.Config.MD5Helper.MD5("https://yourfileUrlOrKey")'

Thanks Jason
I share with you how part of my code is:
var key = ImageService.Instance.Config.MD5Helper.MD5("https://yourfileUrlOrKey");
var imagePath = await ImageService.Instance.Config.DiskCache.GetFilePathAsync(key);
var tempFile = Path.Combine(Path.GetTempPath(), "test.jpg");
if (File.Exists(tempFile))
{
File.Delete(tempFile);
}
File.Copy(imagePath, tempFile);
await Share.RequestAsync(new ShareFileRequest
{
Title = "Test",
File = new ShareFile(tempFile)
});
The temporary file I believe, since the cached file has no extension and the applications do not recognize the type.

Related

Save an Image with a new file name [ImageSharp]

I have upgraded my project from .net framework to .net 6 (core). In my project, there are many places where Bitmap is used. I have read in the microsoft documentations that System.Drawing.Common will only support the Windows platform and even after adding the EnableUnixSupport configuration, it will not be supported in net7.So, now I am using ImageSharp.Web. I have the scenario where I save a file as Image (the format is .tiff) then I read from that path as bitmap and save as PNG ( due to some business rule)
Following is the line of code I am trying change:
Bitmap.FromFile(completePath).Save(pngPath, ImageFormat.Png);
This is the code I have converted into. The only issue is how to save as a new file name as the Tiff file has tiff in the file name.
string extension = _GetExtension(img.ContentType);
if (extension == Constants.TiffExtension)
{
fileName = fileName.Replace(Constants.TiffExtension, "PNG");
using (var outputStream = new FileStream(completePath, FileMode.CreateNew))
{
var image = SixLabors.ImageSharp.Image.Load(completePath);
image.SaveAsync(outputStream, new PngEncoder()); //how to save new file name?
}
}
You can use the image.Save(fileName); overload to save a image to a file. The file name overload that takes just a path will automatically choose the correct encoder based on the file extension.
I was using the ImageSharp.Web package while the one I needed was the basic ImageSharp package. Special thanks to #James South for correcting me and #tocsoft for the guidance.
I have fixed it by the following code which is working:
if (extension == Constants.Conversion.TiffExtension)
{
using (SixLabors.ImageSharp.Image image = SixLabors.ImageSharp.Image.Load(completePath))
{
string pngPath = completePath.Replace(Constants.Conversion.TiffExtension, Conversion.DefaultExtension);
image.Save(pngPath);
fileName = fileName.Replace(Constants.Conversion.TiffExtension, Conversion.DefaultExtension);
}
}

What is the path of the Json file in Android at Xamarin.Forms?

I am developing an application for Android using Xamarin.
I have created a JsonData folder in the Android project and created a Setting.json file.
\MyApp\MyApp.Android\JsonData\Setting.json
In the properties, we set the Copy when new.
The following folders in the local environment contain the files.
\MyApp\MyApp.Android\bin\Debug\JsonData\Setting.json
I want to load this file in the actual Android device.
When I do this, it tells me that the file is missing.
Could not find a part of the path "/JsonData/Setting.json."
Try
{
var text = File.ReadAllText("JsonData/Setting.json", Encoding.UTF8);
var setting = JsonConvert.DeserializeObject<Setting>(text);
}
catch(Exception exception)
{
var error = exception.Message;
}
What is the path of the file in Android?
I think you're using File Handling in Xamarin.Forms incorrectly.
From the parameter of function File.ReadAllText, the app will access the file system to getSetting.json from folder JsonData in your android device.
The path of the file on each platform can be determined from a .NET Standard library by using a value of the Environment.SpecialFolder enumeration as the first argument to the Environment.GetFolderPath method. This can then be combined with a filename with the Path.Combine method:
string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "temp.txt");
And you can read the file by code:
string text = File.ReadAllText(fileName);
In addition, from your code,I guess you want to Load your Embedded file( Setting.json) as Resources,right?
In this case,we should make sure the Build Action of your Setting.json is Embedded Resource.
And GetManifestResourceStream is used to access the embedded file using its Resource ID.
You can refer to the following code:
var assembly = IntrospectionExtensions.GetTypeInfo(typeof(LoadResourceText)).Assembly;
Stream stream = assembly.GetManifestResourceStream("YourAppName.JsonData.Setting.json");
string text = "";
using (var reader = new System.IO.StreamReader (stream))
{
text = reader.ReadToEnd ();
}
For more , you can check document : File Handling in Xamarin.Forms.
And you can also check the sample code here: https://learn.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/workingwithfiles/ .

How to convert the ImageSource.FromFile to stream in Xamarin.Forms?

I want to convert Image to stream from the ImageSource.FromFile.
My Code:
string location = Path.Combine(FileSystem.AppDataDirectory, "data", "Demo.jpg");
image.Source = ImageSource.FromFile(location);
The image is shown properly but I want to convert this image to Stream in Forms.UWP.
I tried the await StorageFile.GetFileFromApplicationUriAsync() this code to get the stream of the image from the location but it throws an exception.
Please suggest me how to convert the image from the file to stream in UWP?
Santhiya A
This path Path.Combine(FileSystem.AppDataDirectory, "data", "Demo.jpg"); is app's local path within UWP platform. And it is not app installation path. if place the Demo.jpg in your project folder, you will not find it with above path. And the parameter of ImageSource.FromFile(string file) is file name, but not the complete path. For the detail please refer this case reply.
I tried the await StorageFile.GetFileFromApplicationUriAsync() this code to get the stream of the image from the location but it throws an exception.
For UWP platform, you could use the following to converter the image file(build property is Content) to steam. For more please refer this document.
private async Task<Stream> GetStreamAsync()
{
var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Demo.jpg"));
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
return stream.AsStream();
}
And if you want use above in Xamarin Forms client project, you need package above method with DependencyService.

Read (audio) file from subfolder in AndroidAssets in Xamarin.Forms

I try to eneable audio in my Xamarin.Forms application. I want to have the audio files in a Subfolderof the Assetsfolder like this Assets/Subfolder/Audio.mp3
I have found a plugin SimpleAudioPlayer which provide an example.
The following code works like provided.
var player = Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current;
player.Load("Audio.mp3");
Now I want to place the audio file in a subfolder and I tried to call
player.Load("Subfolder/Audio.mp3");
But I get an Java.IO.FileNotFoundException
I looked then into the implementation of the Load function and I fould the following code
public bool Load(string fileName)
{
player.Reset();
AssetFileDescriptor afd = Android.App.Application.Context.Assets.OpenFd(fileName);
player?.SetDataSource(afd.FileDescriptor, afd.StartOffset, afd.Length);
return PreparePlayer();
}
where the filename is pasted to the Assets.OpenFd() function. which returns an AndroidFileDesriptor
The documentation does not really provide any information from Microsoft and from the Android site.
My questions are
How can I receive the file from the subfolder in Android Assets?
What can I paste into the Assets.OpenFd() function (subfolders etc)?
I would appreciate any advice, since after a long time trying to resolve it I don't really have an idea.
According to the docs of the package, you won't be able to do just that because you have to use player.Load(GetStreamFromFile("mysound.wav")); where GetStreamFromFile is basically
Stream GetStreamFromFile(string filename)
{
var assembly = typeof(App).GetTypeInfo().Assembly;
var stream = assembly.GetManifestResourceStream("App." + filename);
// Obviously App in the line above should be replaced with your app
return stream;
}
And secondly you have to player.Load(GetStreamFromFile("Subfolder.mysound.wav")); where Subfolder is the name of your subfolder.

How to upload files in flex using PyAMF or PhpAMF? client side, and very little server side help needed

Hy!
I need to upload a group of images using flex with robotlegs.
I need a progress bar to work when image is uploading.
It might upload 1 image or more at the time.
I want to know if uploading byteArray to server and then save the image is too heavy for the server.
In the server side I have a method that is made by pyamf, and looks like this:
.
def upload_image(input):
# here does stuff. I need to be able to get parametters like this
input.list_key
# and here I need some help on how to save the file
Thanks ;)
I had to tackle a similar problem (uploading single photo from Flex to Django) while working on captionmash.com, maybe it can help you. I was using PyAMF for normal messaging but FileReference class had a built in upload method, so I chose the easy way.
Basically system allows you to upload a single file from Flex to Google App Engine, then it uses App Engine's Image API to create thumbnail and also convert image to JPEG, then upload it to S3 bucket. boto library is used for Amazon S3 connection, you can view the whole code of the project here on github.
This code is for single file upload only, but you should be able to do multi-file uploads by creating an array of FileReference objects and calling upload method on all of them.
The code I'm posting here is a bit cleaned up, if you still have problems you should check the repo out.
Client Side (Flex):
private function upload(fileReference:FileReference,
album_id:int,
user_id:int):void{
try {
//500 kb image size
if(fileReference.size > ApplicationConstants.IMAGE_SIZE_LIMIT){
trace("File too big"+fileReference.size);
return;
}
fileReference.addEventListener(Event.COMPLETE,onComplete);
var data:URLVariables = new URLVariables();
var request:URLRequest = new URLRequest(ApplicationConstants.DJANGO_UPLOAD_URL);
request.method = URLRequestMethod.POST;
request.data = data;
fileReference.upload(request,"file");
//Popup indefinite progress bar
} catch (err:Error) {
trace("ERROR: zero-byte file");
}
}
//When upload complete
private function onComplete(evt:Event):void{
fileReference.removeEventListener(Event.COMPLETE,onComplete);
//Do other stuff (remove progress bar etc)
}
Server side (Django on App Engine):
Urls:
urlpatterns = patterns('',
...
(r'^upload/$', receive_file),
...
Views:
def receive_file(request):
uploadService = UploadService()
file = request.FILES['file']
uploadService.receive_single_file(file)
return HttpResponse()
UploadService class
import uuid
from google.appengine.api import images
from boto.s3.connection import S3Connection
from boto.s3.key import Key
import mimetypes
import settings
def receive_single_file(self,file):
uuid_name = str(uuid.uuid4())
content = file.read()
image_jpeg = self.create_jpeg(content)
self.store_in_s3(uuid_name, image_jpeg)
thumbnail = self.create_thumbnail(content)
self.store_in_s3('tn_'+uuid_name, thumbnail)
#Convert image to JPEG (also reduce size)
def create_jpeg(self,content):
img = images.Image(content)
img_jpeg = images.resize(content,img.width,img.height,images.JPEG)
return img_jpeg
#Create thumbnail image using file
def create_thumbnail(self,content):
image = images.resize(content,THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT,images.JPEG)
return image
def store_in_s3(self,filename,content):
conn = S3Connection(settings.ACCESS_KEY, settings.PASS_KEY)
b = conn.get_bucket(BUCKET_NAME)
mime = mimetypes.guess_type(filename)[0]
k = Key(b)
k.key = filename
k.set_metadata("Content-Type", mime)
k.set_contents_from_string(content)
k.set_acl("public-read")

Resources