nuffnang leaderboard

Nov 27, 2012

[WP7] Posting an image to Facebook

<pre class="brush:c#;">

Requirements:
Facebook c# SDK 5.4.1.0 (Tried on OS 7.1)
FB App code


Convert the writeablebitmap to byte array
// convert writeablebitmap to byte array for upload
byte[] buffer = null;

using (MemoryStream ms = new MemoryStream())
{
     Extensions.SaveJpeg(MyGlobals.bmp2, ms, MyGlobals.bmp2.PixelWidth, MyGlobals.bmp2.PixelHeight, 0, 100);
     buffer = ms.ToArray();
}


Post process
// post to facebook
var fb = new FacebookClient(_accessToken);

fb.PostCompleted += (o, args) =>
{
     // incase you support cancellation, make sure to check
     // e.Cancelled property first even before checking (e.Error!=null).
     if (args.Cancelled)
     {
         // for this example, we can ignore as we don't allow this
         // example to be cancelled.

         // you can check e.Error for reasons behind the cancellation.
         var cancellationError = args.Error;
      }
      else if (args.Error != null)
      {
           // error occurred
           Dispatcher.BeginInvoke(() =>
           {
                MessageBox.Show(args.Error.Message);
           });
           }
       else
       {
           // the request was completed successfully
           var result = (IDictionary)args.GetResultData();
           _lastMessageId = (string)result["id"];

          // make sure to be on the right thread when working with ui.
          Dispatcher.BeginInvoke(() =>
          {
             MessageBox.Show("Message Posted successfully");
             txtMessage.Text = string.Empty;
             btnDeleteLastMessage.IsEnabled = true;
          });
          }
       };

       var facebookUpload = new Facebook.FacebookMediaObject { FileName = Guid.NewGuid() + ".jpg", ContentType = "image/jpg" };
       facebookUpload.SetValue(buffer); 
       var photoDetails = new Dictionary(); 
       photoDetails.Add("message", "sample"); 
       photoDetails.Add("image", facebookUpload); 
       fb.PostAsync(@"/photos", photoDetails);

            // alternative way
            /*
            var parameters = new Dictionary();
            parameters["message"] = "testing";
            parameters["file"] = new FacebookMediaObject
                        {
                            ContentType = "image/jpeg",
                            FileName = "image.jpeg",
                        }.SetValue(buffer);

            fb.PostAsync("me/photos", parameters);
            */

No comments:

Post a Comment

nuffnang rectangle