Reputation: 167
How can I upload an image properly from Windows Phone where the image source is a PhotoResult from a PhotoChooserTask? I'm using RestSharp for this, but it only uploads a big bunch of zeroes to my server.
Here's the code part I have trobule with:
using (MemoryStream memo = new MemoryStream())
{
appGlobal.appData.selectedPhoto.ChosenPhoto.CopyTo(memo);
byte[] imgArray = new byte[appGlobal.appData.selectedPhoto.ChosenPhoto.Length];
memo.Read(imgArray, 0, imgArray.Length);
request.AddFile("image", imgArray, "image", "image/jpeg");
}
I can't seem to figure out how am I supposed to convert PhotoResult.ChosenPhoto (which is a PhotoStream) to a byte array.
Any thoughts?
Upvotes: 1
Views: 598
Reputation: 167
Ok I found out what the problem was. It seems that when you get the PhotoResult back from a chooser task let it be PhotoChooserTask or CameraCaptureTask, the stream's position isn't set to 0. So you'll have to set it manually before reading the bytes out from it. Here's the fixed code for my question:
byte[] imgArray = new byte[(int)appGlobal.appData.selectedPhoto.ChosenPhoto.Length];
appGlobal.appData.selectedPhoto.ChosenPhoto.Position = 0;
appGlobal.appData.selectedPhoto.ChosenPhoto.Read(imgArray, 0, (int)appGlobal.appData.selectedPhoto.ChosenPhoto.Length);
appGlobal.appData.selectedPhoto.ChosenPhoto.Seek(0, SeekOrigin.Begin);
request.AddFile("image", imgArray, "image");
Also thanks for the help KooKiz. :)
Upvotes: 1
Reputation: 39007
You're mixing two approaches in your code.
Either directly read the contents of the stream in a byte array:
byte[] imgArray = new byte[appGlobal.appData.selectedPhoto.ChosenPhoto.Length];
appGlobal.appData.selectedPhoto.ChosenPhoto.Read(imgArray, 0, imgArray.Length);
request.AddFile("image", imgArray, "image", "image/jpeg");
Or copy the stream to a MemoryStream then use the ToArray
method:
using (MemoryStream memo = new MemoryStream())
{
appGlobal.appData.selectedPhoto.ChosenPhoto.CopyTo(memo);
byte[] imgArray = memo.ToArray();
request.AddFile("image", imgArray, "image", "image/jpeg");
}
Upvotes: 0