首页 > 解决方案 > How can I save a captured picture from the user to the cosmos db in xamarin forms?

问题描述

It's supposed that I allow the user to capture a picture using his camera or pick one from the gallery. I have a property called picture in the model which it's supposed to have the path of the image. How can I save this image to the database and save its path in the property?

标签: c#xamlxamarinxamarin.forms

解决方案


如何将此图像保存到数据库并将其路径保存在属性中?

您可以将图像文件作为字节数组存储到数据库中。你是如何挑选或捕捉照片的?您可以使用Xam.Plugin.Media 插件来实现该功能。该库提供了相关的方法,可以帮助轻松保存图片。

从图库中挑选照片后,尝试使用MediaFile.Path命令获取图像文件的路径。您可以使用GetStream()方法获取流并将流转换为字节数组。然后将 byte[] 和路径字符串存储在数据库中。

var image_file = await Plugin.Media.CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions() { });
var Image_stream = image_file.GetStream();
image_file.Dispose();

//convert the image stream to byte array
private byte[] GetImageBytes(Stream stream)
{
    byte[] ImageBytes;
    using (var memoryStream = new System.IO.MemoryStream())
    {
        stream.CopyTo(memoryStream);
        ImageBytes = memoryStream.ToArray();
    }
    return ImageBytes;
}

推荐阅读