title: Is there a cross-platform solution to ImageSource to byte[]?
body: <p>I did researches and fell on this solution: <a href="http://forums.xamarin.com/discussion/22682/is-there-a-way-to-turn-an-imagesource-into-a-byte-array" rel="noreferrer">http://forums.xamarin.com/discussion/22682/is-there-a-way-to-turn-an-imagesource-into-a-byte-array</a></p>
  
  <p>Initial question: <a href="http://forums.xamarin.com/discussion/29569/is-there-a-cross-platform-solution-to-imagesource-to-byte#latest" rel="noreferrer">http://forums.xamarin.com/discussion/29569/is-there-a-cross-platform-solution-to-imagesource-to-byte#latest</a></p>
  
  <p>We want to upload an image through a HTTP Post, here's what we tried:</p>
  
  <pre><code>HttpClient httpClient = new HttpClient ();
  byte[] TargetImageByte = **TargetImageSource**; //How to convert it to a byte[]?
  HttpContent httpContent = new ByteArrayContent (TargetImageByte);
  httpClient.PostAsync ("https://api.magikweb.ca/debug/file.php", httpContent);
  </code></pre>
  
  <p>We also are having a hard time with the libraries we gotta include in the using clauses. It seems like <code>using System.IO;</code> works, but it doesn't give us access to classes like <code>FileInfo</code> or <code>FileStream</code>. </p>
  
  <p>Anybody has any idea how this can be done aside from custom platform-specific converters?
  Possibly a Xamarin.Forms.ImageSource function toByte()?</p>
  
  <p>Lemme know if you need more information.</p>
  
  <p><code>TargetImageSource</code> is a <code>Xamarin.Forms.ImageSource</code>.</p>
  
  <p><code>ImageSource TargetImageSource = null;</code></p>
  
  <p><strong>Solution</strong> (Sten was right)</p>
  
  <p>The <code>ImageSource</code> has to originate from another type to exist, that previous type can be converted to a <code>byte[]</code>. In this case, I use the <strong>Xamarin.Forms.Labs</strong> to take a picture and it returns a <code>MediaFile</code> in which a <code>FileStream</code> is accessible through the <code>Source</code> property.</p>
  
  <pre><code>//--Upload image
  //Initialization
  HttpClient httpClient = new HttpClient ();
  MultipartFormDataContent formContent = new MultipartFormDataContent ();
  //Convert the Stream into byte[]
  byte[] TargetImageByte = ReadFully(mediaFile.Source);
  HttpContent httpContent = new ByteArrayContent (TargetImageByte);
  formContent.Add (httpContent, "image", "image.jpg");
  //Send it!
  await httpClient.PostAsync ("https://api.magikweb.ca/xxx.php", formContent);
  
  App.RootPage.NavigateTo (new ClaimHistoryPage());
  </code></pre>
  
  <p>The function:</p>
  
  <pre><code>public static byte[] ReadFully(Stream input)
  {
      using (MemoryStream ms = new MemoryStream()){
          input.CopyTo(ms);
          return ms.ToArray();
      }
  }
  </code></pre>