How to get file image source from file path in Xamarin Forms here i have stored a folder locally by using dependency services.
_fileHelper = _fileHelper ?? DependencyService.Get<IFileHelper>();
profiletap.Tapped += async (s, e) =>
{
var file = await CrossMedia.Current.PickPhotoAsync();
if (file == null)
return;
await DisplayAlert("File Location", file.Path, "OK");
profile.Source = im;
imageName = "SomeUniqueFileName" + DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss-tt");
filePath = _fileHelper.CopyFile(file.Path, imageName);
im = ImageSource.FromFile(filePath)
}
i want to upload image from media picker permanently so that i can not loose image once uploaded public string CopyFile(string sourceFile, string destinationFilename, bool overwrite = true)
{
if (!File.Exists(sourceFile)) { return string.Empty; }
string fullFileLocation = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) );
File.Copy(sourceFile, fullFileLocation, overwrite);
return fullFileLocation;
}
im = ImageSource.FromStream(()=> file.GetStream());
Related
Hello, would any of you send a working code to download a photo from a given http address on android Xamarin c #?
First, I need to create a new folder for my application files.
My goal is to download the file from the internet to my Android folder (saving this file with its original name is best).
The next step is to display the image from that folder in "ImageView". It is also important that there are permissions in android and I do not fully understand it.
Could any of you send it to me or help me understand it and explain the topic?
*Actually i have this code:
string address = "https://i.stack.imgur.com/X3V3w.png";
using (WebClient webClient = new WebClient())
{
webClient.DownloadFileCompleted += WebClient_DownloadFileCompleted;
webClient.DownloadFile(address, Path.Combine(pathDire, "MyNewImage1.png"));
//System.Net.WebException: 'An exception occurred during a WebClient request.'
}
Loading image from url and display in imageview.
private void Btn1_Click(object sender, System.EventArgs e)
{
var imageBitmap = GetImageBitmapFromUrl("http://xamarin.com/resources/design/home/devices.png");
imagen.SetImageBitmap(imageBitmap);
}
private Bitmap GetImageBitmapFromUrl(string url)
{
Bitmap imageBitmap = null;
using (var webClient = new WebClient())
{
var imageBytes = webClient.DownloadData(url);
if (imageBytes != null && imageBytes.Length > 0)
{
SavePicture("ImageName.jpg", imageBytes, "imagesFolder");
imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
}
}
return imageBitmap;
}
download image and save it in local storage.
private void SavePicture(string name, byte[] data, string location = "temp")
{
var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
documentsPath = System.IO.Path.Combine(documentsPath, "Orders", location);
Directory.CreateDirectory(documentsPath);
string filePath = System.IO.Path.Combine(documentsPath, name);
using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
{
int length = data.Length;
fs.Write(data, 0, length);
}
}
you need to add permission WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE in AndroidMainfeast.xml, then you also need to Runtime Permission Checks in Android 6.0.
private void checkpermission()
{
if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) == (int)Permission.Granted)
{
// We have permission, go ahead and use the writeexternalstorage.
}
else
{
// writeexternalstorage permission is not granted. If necessary display rationale & request.
}
if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) == (int)Permission.Granted)
{
// We have permission, go ahead and use the ReadExternalStorage.
}
else
{
// ReadExternalStorage permission is not granted. If necessary display rationale & request.
}
}
I have an application that creates a .vcf file after you input data. it stores storage provided by the phone, I want to click on a list view item and get the vcf file and share it via Email, SMS, WhatsApp, Skype etc how do I implement this in IOS and Android.
Thank you
I have got the answer of creating .vcf file which is given below. and for share that file follow this link : https://github.com/adamped/ShareDialog
private void Share_Clicked(object sender, EventArgs e)
{
try
{
var _btn = sender as Button;
var record = _btn.BindingContext as Contact;
int tempcontactID = record.ContactID;
if (record.CardFrontImage == null)
{
record.CardImage = record.CardBackImage;
}
else
{
record.CardImage = record.CardFrontImage;
}
string baseimage = Convert.ToBase64String(record.CardImage);
var vcf = new StringBuilder(); //vcf code start
vcf.AppendLine("BEGIN:VCARD");
vcf.AppendLine("VERSION:3.0");
vcf.AppendLine($"N:{record.ContactName};{string.Empty}; ;;");
vcf.AppendLine($"FN:{record.ContactName}");
vcf.AppendLine($"ORG:{record.CompanyName}");
vcf.AppendLine($"TITLE:{record.Designation}");
vcf.AppendLine($"PHOTO;ENCODING=BASE64;TYPE=PNG:{baseimage}");
vcf.AppendLine($"TEL;TYPE=work,voice;VALUE=uri:tel:{record.PhoneNumber}");
vcf.AppendLine("END:VCARD");
string fileName = Path.Combine("/storage/emulated/0/Android/data/com.Gamma.GammaNetworkingApp/files/", record.ContactID + record.ContactName + ".vcf");
using (var writer = new StreamWriter(fileName))
{
writer.Write(vcf.ToString());
}
string text = File.ReadAllText(fileName);
bool doesExist = File.Exists(fileName);
if (doesExist == true)
{
var share = DependencyService.Get<IShare>();
share.Show("Contact share", record.ContactName, fileName);
}
}
catch (Exception ex)
{
string test = ex.ToString();
Navigation.PushAsync(new HomePage());
}
}
I have worked with pdfjs and its working fine with local storage pdf, but I have another issue: I need to display pdf from WEB API, as I have stored binary data of pdf which I need to display?? this is my code
public pdfjsPage(string url)
{
InitializeComponent();
var localPath = string.Empty;
if (Device.RuntimePlatform == Device.Android)
{
var dependency = DependencyService.Get<ILocalFileProvider>();
if (dependency == null)
{
DisplayAlert("Error loading PDF", "Computer says no", "OK");
return;
}
var fileName = Guid.NewGuid().ToString();
// Download PDF locally for viewing
using (var httpClient = new HttpClient())
{
var pdfStream = Task.Run(() => httpClient.GetStreamAsync(url)).Result;
localPath =
Task.Run(() => dependency.SaveFileToDisk(pdfStream, $"{fileName}.pdf")).Result;
}
if (string.IsNullOrWhiteSpace(localPath))
{
DisplayAlert("Error loading PDF", "Computer says no", "OK");
return;
}
}
if (Device.RuntimePlatform == Device.Android)
PdfView.Source = $"file:///android_asset/pdfjs/web/viewer.html?file={WebUtility.UrlEncode(localPath)}";
else
PdfView.Source = url;
}
This is working with local pdf, but I have WEB API URL and I need to get pdf from there online.
This is the link from where I retrieve it: http://veezo2007pkk.somee.com/api/DiagnosticDetail/RetrieveFile/1
After saving your PDF to your device, pass the path to an Intent.
//Example
var fileName = "/storage/emulated/0/yourPDF.pdf"
Uri pdfPath = Uri.FromFile(new File(fileName));
Intent intent = new Intent(Intent.ActionView);
intent.SetDataAndType(pdfPath, "application/pdf");
intent.SetFlags(ActivityFlags.NewTask);
Android.App.Application.Context.StartActivity(intent);
How to get file path on Xamarin.Plugin.FilePicker? I am getting file name and byteData but how to get file path? Here is my code-
try
{
FileData filedata = new FileData();
var crossFileData = CrossFilePicker.Current;
filedata = await crossFileData.PickFile();
byte[] data = filedata.DataArray;
string name = filedata.FileName;
AtttchFileName.Text = name;
if(AtttchFileName.Text==null)
{
DoneAttachment.IsEnabled = false;
}
else
{
DoneAttachment.IsEnabled = true;
}
foreach (byte b in filedata.DataArray)
{
string attachment = b.ToString();
}
}
catch (Exception ex)
{
string msg = ex.Message;
}
How to achieve this?
If a path, or a file Uri, is available, it is assigned to the FileData.FilePath property:
filedata = await crossFileData.PickFile();
var filePath = filedata.FilePath;
re: Plugin.FilePicker.Abstractions/FileData.cs#L67
You can use this FilePicker for Xamarin, since it has file path like you need.
FileData filedata = await CrossFilePicker.Current.PickFile();
string filepath = filedata.FilePath;
Nuget package for it is here.
the following code is what I use to grab a voice file to send an email as an attachment. However, I am not able to find this file. no clue where it is stored. (this is what I see when I hover the path /storage/emulated/0/test.mp4). the storage folder is empty even when this run, for this reason, the attachment can't be sent. any ideas? Thank you! updated code
string path = "";
public Recorder_Droid()
{
var sqlliteFilname = "test.mp4";
string filePath = global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
path = Path.Combine(filePath, sqlliteFilname);
_recorder = new MediaRecorder();
_player = new MediaPlayer();
_player.Completion += (sender, e) => {
_player.Reset();
};
}
MediaRecorder _recorder;
MediaPlayer _player;
public void PlayAudio()
{
if (File.Exists(path))
{
File.Delete(path);
}
if (_recorder == null)
{
_recorder = new MediaRecorder();
}
_recorder.Reset();
_recorder.SetAudioSource(AudioSource.Mic);
_recorder.SetOutputFormat(OutputFormat.Mpeg4);
_recorder.SetAudioEncoder(AudioEncoder.Aac);
_recorder.SetOutputFile(path);
_recorder.Prepare(); // Prepared state
_recorder.Start(); // Recording state.
return;