问题
I am developing an app with Xamarin Android, I want to select an image from the gallery and save it to a SQL Server database using a WCF service.
My code is working except one part that the image want to convert and save into the database.
My column datatype for the image is: varbinary(MAX).
My variable definition for the image in the project is: byte[] imageByte;
Some part of my code is below:
private void PicSelected()
{
//mSelectedPic = selectedPic;
Intent = new Intent();
Intent.SetType("image/*");
Intent.SetAction(Intent.ActionGetContent);
StartActivityForResult(Intent.CreateChooser(Intent, "Select Picture"),0);
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (resultCode == Result.Ok)
{
Stream stream = ContentResolver.OpenInputStream(data.Data);
Bitmap bitmap = BitmapFactory.DecodeStream(stream);
MemoryStream memStream = new MemoryStream();
bitmap.Compress(Bitmap.CompressFormat.Webp, 100, memStream);
byte[] picData = memStream.ToArray();
picDataPublic = picData;
}
}
This code selects a picture from the gallery and then convert it to byte array (byte[]), I think the problem is here.
Then the code shown below communicates with the database and passes the data to the WCF service.
_btnAdd.Click += async (sender, args) =>
{
string sUrl = "http://192.168.43.31/Service1.svc/insertIntoTableAdvertise";
string sContentType = "application/json";
CheckAppPermissions();
JObject oJsonObject = new JObject();
oJsonObject.Add("TxtGroup", _edtAdvGrouping.Text);
oJsonObject.Add("TxtTitle", _edtTitle.Text);
oJsonObject.Add("TxtDate", "1397/10/14");
oJsonObject.Add("TxtLocation", "شاهین");
oJsonObject.Add("TxtNumber", _edtNumber.Text);
oJsonObject.Add("TxtPrice", _edtPrice.Text);
oJsonObject.Add("TxtExpression", _edtExpression.Text);
oJsonObject.Add("ImageByte", Convert.ToBase64String(picDataPublic));
//oJsonObject.Add("ImageByte", "");
try
{
var content = new StringContent(oJsonObject.ToString(), Encoding.UTF8, sContentType);
var response = await httpClient.PostAsync(sUrl, content);
var responseContent = await response.Content.ReadAsStringAsync();
if (responseContent == "1")
{
Toast.MakeText(this, "Success. " + responseContent, ToastLength.Short).Show();
}
else
{
Toast.MakeText(this, "Failure." + responseContent, ToastLength.Short).Show();
}
}
catch (Exception ex)
{
Toast.MakeText(this, ex.Message.ToString(), ToastLength.Short).Show();
}
finally
{
this.Finish();
}
};
When the code is:
oJsonObject.Add("ImageByte", "");
the service works and returns a success message, but when this condition:
oJsonObject.Add("ImageByte", Convert.ToBase64String(picDataPublic));
the service doesn't work.
I think the problem is with converting the image to the byte array.
Please help me with this problem
来源:https://stackoverflow.com/questions/54242363/saving-image-into-sql-server-with-web-service-in-xamarin-android