How can we received a image file from imageToUploa

2019-08-16 16:44发布

问题:

How to receive a 'photo' displayed under <Image x:Name="imageToUpload" WidthRequest="40" HeightRequest="40"/> and pass to a variable in Xamarin Forms ? I am getting the file/image at this line var file = await CrossMedia.Current.TakePhotoAsync(.... would need to passed into RegisterSave_OnClicked() method and further save into SQLite database

 var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
                {
                    Directory = "Pictures",
                    Name = "test.jpg",
                    PhotoSize = PhotoSize.Small,
                    CompressionQuality = 75,
                    CustomPhotoSize = 5,
                    DefaultCamera = CameraDevice.Front,
                });

//Register button save code given below:

public async void RegisterSave_OnClicked(object sender, EventArgs e)
        {
            int count = (from y in conn.Table<PlayerDetails>().Where(y => y.Email == playerEmail) select y).Count();
            if(count!=0)
            {
                var updatePlayer = (from y in conn.Table<PlayerDetails>().Where(y => y.Email == playerEmail) select y);
                foreach (var update_Player in updatePlayer)
                {
                    update_Player.FullName = fullNameEntry.Text;
                    update_Player.Mobile = mobileEntry.Text;
                    // code continues here .......
                    // assuming conn is an SQLiteConnection
                    conn.Update(update_Player);   
                }               
                await Navigation.PushAsync(new MainPage());
            }
            else
            {
                PlayerDetails playerDetails = new PlayerDetails();
                playerDetails.FullName = fullNameEntry.Text;
                playerDetails.Mobile = mobileEntry.Text;
                // code continues here .......

回答1:

If you want to save the imageSource to database , we can convert it to a byte[] array .

public  byte[] ReadFully(Stream input)
{
    byte[] buffer = new byte[16*1024];
    using (MemoryStream ms = new MemoryStream())
    {
        int read;
        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            ms.Write(buffer, 0, read);
        }
        return ms.ToArray();
    }
}

MediaFile has GetStream().

You could use this to the Stream and then convert that to a byte[]. Here is one way to do that:

1.define a stream in your contentPage

Stream imageStream;

And init it after you take the photo .

imageStream = file.GetStream();

And call it when you click the button

var imageArr= ReadFully(imageStream );