1

i need to upload image as binary data and retrieve here is my code 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;

            }
        }

Kindly i need to convert image to binary data and save it to sql server. I am able to save other data to sql server, but dont know how to convert image to binary and save into database and how to retrieve and show in image.

waqas waqas
  • 197
  • 9
  • 22

1 Answers1

1

As a best practice, you should not save the image directly into SQL server unless it is really necessary. Read more in this link.

To answer your question, follow the below steps.

  1. Convert the image into 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. Now the image will be in a string format. Do the inserting.

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

  3. When you want to display back the image, retrieve the image from SQL using SELECT query.

  4. Convert the Base64 back into Image format.

    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;
    }
    

For references: Bas64 to image, Best practices

Selvarathinam Vinoch
  • 1,080
  • 3
  • 13
  • 23