Xamarin表单-如何使用SQL Server Web API上传和检索图像

时间:2018-06-25 07:44:00

标签: c# sql-server xamarin xamarin.forms

我需要将图像作为二进制数据上传并在这里检索,这是我的代码 Web API

   [ResponseType(typeof(tblEmpPicture))]
        public IHttpActionResult PosttblEmpPicture(tblEmpPicture tblEmpPicture)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.tblEmpPictures.Add(tblEmpPicture);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateException)
            {
                if (tblEmpPictureExists(tblEmpPicture.intEmpCode))
                {
                    return Conflict();
                }
                else
                {
                    throw;
                }
            }

            return CreatedAtRoute("DefaultApi", new { id = tblEmpPicture.intEmpCode }, tblEmpPicture);
        }

MainPage.xaml

<Image x:Name="userImage" Source="{Binding Pic.vbrPicture, Mode=TwoWay}" Aspect="AspectFill" WidthRequest="85" HeightRequest="85" >

MainPage.cs

await CrossMedia.Current.Initialize();

                if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
                {
                    await DisplayAlert("No Camera", ":( No camera available.", "OK");
                    return;
                }

                var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
                {
                    Directory = "Sample",
                    Name = "test.jpg"
                });

                if (file == null)
                    return;

                await DisplayAlert("File Location", file.Path, "OK");

                userImage.Source = ImageSource.FromStream(() =>file.GetStream());


                await ((MainViewModel)this.BindingContext).PutUserPicCommand();

MainVewModel

private tblEmpPicture _Pic = new tblEmpPicture();
        public tblEmpPicture Pic
        {
            get { return _Pic; }
            set
            {
                _Pic = value;
                OnPropertChanged();
            }
        }

public async Task PutUserPicCommand()
        {
            try
            {
                IsBusy = true;

                // Call your web service here
                var employeesTaskServices = new TaskServices();
                await employeesTaskServices.PutUserPicAsync(_Pic);
            }
            catch (Exception ex)
            {
                // Handle exception
            }
            finally
            {
                IsBusy = false;

            }
        }

请注意,我需要将图像转换为二进制数据并将其保存到sql server。我能够将其他数据保存到sql server,但是不知道如何将图像转换为二进制文件并保存到数据库中,以及如何检索和显示图像。

1 个答案:

答案 0 :(得分:0)

作为最佳实践,除非确实需要,否则不应将映像直接保存到SQL Server中。 Read more in this link.

要回答您的问题,请按照以下步骤操作。

  1. 将图像转换为Base64。

    public static async Task<string> Convertbase64Async (Stream stream)
    {
        var bytes = new byte[stream.Length];
        await stream.ReadAsync(bytes, 0, (int)stream.Length);
        string base64 = Convert.ToBase64String(bytes);
        return base64;
    }
    
  2. 现在图像将为字符串格式。进行插入。

    INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);

  3. 当您要显示图像时,请使用SELECT查询从SQL中检索图像。

  4. 将Base64转换回图像格式。

    public Image LoadImage(String base_64)
    {
        byte[] bytes = Convert.FromBase64String(base_64);
    
        Image image;
        using (MemoryStream ms = new MemoryStream(bytes))
        {
            image = Image.FromStream(ms);
        }
    
        return image;
    }
    

有关参考:Bas64 to imageBest practices