Xamarin form - how to upload and retrieve image using sql server web api
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.
-
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; }
-
Now the image will be in a string format. Do the inserting.
INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);
When you want to display back the image, retrieve the image from SQL using SELECT query.
-
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