Convert Image to ByteArray in Xamarin Forms - xamarin

May I know how to convert image (take from folder/take from Camera) to Byte Array?
& also convert Byte Array to image?
Take Photo From Camera
async void TakePhoto()
{
try
{
var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
Directory = "Sample",
Name = "test.jpg",
//SaveToAlbum = saveToGallery.IsToggled
});
if (file == null)
return;
// await DisplayAlert("File Location", (saveToGallery.IsToggled ? file.AlbumPath : file.Path), "OK");
img.Source = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
file.Dispose();
return stream;
});
}
catch
{
}
}
Take Photo From Folder
async void FromFolder()
{
try
{
Stream stream = null;
var file = await CrossMedia.Current.PickPhotoAsync().ConfigureAwait(true);
if (file == null)
return;
stream = file.GetStream();
file.Dispose();
img.Source = ImageSource.FromStream(() => stream);
}
catch
{
}
}
I dont know where are the location of Image, and where to get the image.
I'm trying to save image into Azure database. But i'm facing problem to convert MediaFile into Byte[]. I'm using Xam.Plugin.Medie ( http://www.nuget.org/packages/Xam.Plugin.Media ) to access camera and gallery. Please kindly guide me how to convert MedieFile into Byte[]. Thank you.
Any sample source code for references

Related

Xamarin Android image Capture by Camera using intent ActionImageCapture, the image quality is low

Im new to Xamarin Android. Now I was trying to capture the image by camera and displaying in imageview but I was facing the problem which is the image quality that captured from camera is low. And I was doing the research from google and i only found the solution which is save the image that captured in to file and retrieve from file. But the solution is only for android studio and xamarin form.
This is the coding for the intent that calling image captured
Intent intent = new Intent(MediaStore.ActionImageCapture);
StartActivityForResult(intent, 1000);
This is the coding for onactivityresult,
if ((requestCode == PickImageId) && (resultCode == Android.App.Result.Ok) && (data != null))
{
base.OnActivityResult(requestCode, resultCode, data);
bitmap = (Bitmap)data.Extras.Get("data");
var dir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDcim);
string filename = System.DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg";
string filePath = System.IO.Path.Combine(dir + "/Camera/", filename);
using (var stream = new MemoryStream())
{
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);
byte[] bitmapData = stream.ToArray();
try
{
System.IO.File.WriteAllBytes(filePath, bitmapData);
bitmap = BitmapFactory.DecodeByteArray(bitmapData, 0, bitmapData.Length);
imgview.SetImageBitmap(bitmap);
}
catch (Exception ex)
{
System.Console.WriteLine(ex.ToString());
}
}
}
I have try to save the image into phone folder which is 'DCIM/Camera/xxx.jpg'. The image that captured and save in folder is success but the image quality still low.
Is there have any solution to increase the quality of the image?
Sorry for my poor english, please provide me suggestion or solution.
Thanks for giving helps
Hello you can use Xamarin Essential Media Picker to take photo.
Here is an example code:
using Xamarin.Essentials;
string PhotoPath="";
public async Task TakePhotoAsync()
{
try
{
var photo = await MediaPicker.CapturePhotoAsync();
await LoadPhotoAsync(photo);
}
catch (FeatureNotSupportedException fnsEx)
{
// Feature is not supported on the device
}
catch (PermissionException pEx)
{
// Permissions not granted
}
catch (Exception ex)
{
Console.WriteLine($"CapturePhotoAsync THREW: {ex.Message}");
}
}
public async Task LoadPhotoAsync(FileResult photo)
{
// canceled
if (photo == null)
{
PhotoPath = null;
return;
}
// save the file into local storage
var newFile = Path.Combine(FileSystem.CacheDirectory, photo.FileName); //or any other Storage Directory
using (var stream = await photo.OpenReadAsync())
using (var newStream = File.OpenWrite(newFile))
await stream.CopyToAsync(newStream);
PhotoPath = newFile;
}

Upload File to rest wep api c#

Hello i try to send Image to Web api from my xamarin-forms app and save it in my database but i have problem with convert to base 64
i Used plugin to pick image and i try to convert it to Image base 64 and it didnt give me corect string image base 64
_aktFile = await CrossMedia.Current.PickPhotoAsync();
if (_aktFile == null)
return;
ImageSource = ImageSource.FromStream(() =>
{
ImageStream = _aktFile.GetStream();
ImageMessageByteArray = new byte[_ImageStream.Length];
ImageStream.Read(_ImageMessageByteArray, 0, (int)_ImageStream.Length);
ImageMessageBase64 = System.Convert.ToBase64String(_ImageMessageByteArray);
return _aktFile.GetStream();
});
_aktFile = await CrossMedia.Current.PickPhotoAsync();
if (_aktFile == null)
return;
else
{
string Base64String = ConvertStreamToBase64(_aktFile);
}
private string ConvertStreamToBase64(Stream stream)
{
if (stream != null)
{
byte[] bytes;
using (var memoryStream = new MemoryStream())
{
stream.Seek(0, SeekOrigin.Begin);
stream.CopyTo(memoryStream);
bytes = memoryStream.ToArray();
}
base64selectedImage = Convert.ToBase64String(bytes);
stream.Seek(0, SeekOrigin.Begin);
}
return base64selectedImage;
}

Xamarin SignaturePad Proper way of using UWP GetImageAsync?

I'm using xamarin SignaturePad.
How to use GetImageAsync properly? because the output is not the same with my input.
I use this code:
var imageStream = await signature.GetImageStreamAsync(SignatureImageFormat.Jpeg);
public static byte[] ConvertStreamToByte(Stream stream)
{
if (stream != null)
{
using (MemoryStream memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
return null;
}
Convert Byte[] to Image.
this.SignatureImage = ImageSource.FromStream(() => new MemoryStream(signatureData.Data));
My input on top.
Bottom pic is the retrieved data.
Is it misuse of GetImageAsync or Wrong Conversion? Help.
var imageStream = await signature.GetImageStreamAsync(SignatureImageFormat.Jpeg
, Color.Black, Color.White);
Need to add color for stroke and backround else it will default to black.

How to get file image source from file path in xamarin

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());

Xamarin.Forms get image path

Using the Xamarin.Forms Camera sample from here - https://github.com/XForms/Xamarin-Forms-Labs-Samples/tree/master/XF.Labs.CameraSample i am able to select or take a photo. I then need to convert this image to binary
so here is the code that selects the image:
private async Task SelectPicture()
{
mediaPicker = DependencyService.Get<IMediaPicker>();
imageSource = null;
var mediaFile = await mediaPicker.SelectPhotoAsync(new CameraMediaStorageOptions
{
DefaultCamera = CameraDevice.Front,
MaxPixelDimension = 400
});
imageSource = ImageSource.FromStream(() => mediaFile.Source);
img.Source = imageSource;
}
and the code that takes the image is very similar
private async Task TakePicture()
{
mediaPicker = DependencyService.Get<IMediaPicker>();
imageSource = null;
var mediaFile = await mediaPicker.TakePhotoAsync(new CameraMediaStorageOptions
{
DefaultCamera = CameraDevice.Front,
MaxPixelDimension = 400
});
imageSource = ImageSource.FromStream(() => mediaFile.Source);
img.Source = imageSource;
}
How do i get the actual string imagePath from the above so that i can call the DependencyService below?
public byte[] ImageToBinary(string imagePath)
{
FileStream fileStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[fileStream.Length];
fileStream.Read(buffer, 0, (int)fileStream.Length);
fileStream.Close();
return buffer;
}
Shouldn't do this stuff tired
It is built in to the MediaFile so the answer is simply mediaFile.Path.ToString();
mediaFile.Path will give you the actual path

Resources