2

PhotoChooserTask が彼を捕まえている写真をTwitterにアップロードしようとしています。私が抱えている問題は、画像を選択してStreamに渡すときの形式であるBitmapImageを渡す方法がわからないことです。

以下は私のコードのサンプルです:

namespace Twitter
{
    public partial class TwitterUploadImage : PhoneApplicationPage
    {

        // Constructor

        TwitterService service;
        private const string consumerKey = "";
        private const string consumerSecret = "";
        private OAuthRequestToken requestToken;
        private OAuthAccessToken accesToken;
        private bool userAuthenticated = false;

        //Uri uri = new Uri("/Background.png", UriKind.Relative);
        //Stream imageStream = Application.GetResourceStream(uri);
        Stream imageStream;
        string namePhoto;

        public TwitterUploadImage()
        {

            InitializeComponent();
            service = new TwitterService(consumerKey,consumerSecret);

            //Chek if we already have the Autehntification data
            var token = getAccessToken();
            if (token != null)
            {
                service.AuthenticateWith(token.Token, token.TokenSecret);
                userAuthenticated = true;
            }
        }

        //protected override void OnNavigatedTo(NavigationEventArgs e)
        //{
        //    // Get a dictionary of query string keys and values. 
        //    IDictionary<string, string> queryStrings = this.NavigationContext.QueryString;

        //    // Ensure that there is at least one key in the query string, and check whether the "FileId" key is present. 
        //    if (queryStrings.ContainsKey("FileId"))
        //    {
        //        // Retrieve the photo from the media library using the FileID passed to the app. 
        //        MediaLibrary library = new MediaLibrary();
        //        Picture photoFromLibrary = library.GetPictureFromToken(queryStrings["FileId"]);

        //        // Create a BitmapImage object and add set it as the image control source. 
        //        // To retrieve a full-resolution image, use the GetImage() method instead. 
        //        BitmapImage bitmapFromPhoto = new BitmapImage();
        //        bitmapFromPhoto.SetSource(photoFromLibrary.GetPreviewImage());
        //        image1.Source = bitmapFromPhoto;
        //    }
        //} 

        private void tweetClick(object sender, RoutedEventArgs e)
        {
            if (userAuthenticated)
                Tweet(Message.Text, imageStream);
            else
                service.GetRequestToken(processRequestToken);
        }

        private void processRequestToken(OAuthRequestToken token, TwitterResponse response)
        {
            if (token == null)
                Dispatcher.BeginInvoke(() => { MessageBox.Show("Error obtaining Request token"); });
            else
            {
                requestToken = token;
                Dispatcher.BeginInvoke(() =>
                {
                    Browser.Visibility = System.Windows.Visibility.Visible;
                    Browser.Navigate(service.GetAuthorizationUri(requestToken));
                });
            }
        }

        private void processAccessToken(OAuthAccessToken token, TwitterResponse response)
        {
            if (token == null)
                Dispatcher.BeginInvoke(() => { MessageBox.Show("Error obtaining Access token"); });
            else
            {
                accesToken = token;
                service.AuthenticateWith(token.Token, token.TokenSecret);
                saveAccessToken(token);
                userAuthenticated = true;
                Dispatcher.BeginInvoke(() =>
                {
                    Tweet(Message.Text, imageStream);
                });
            }
        }

        private void Tweet(string message, Stream ImageStream)
        {
            //SendTweetOptions msg = new SendTweetOptions();
            //msg.Status = message;
            //service.SendTweet(msg, tweetResponse);

            //MediaLibrary library = new MediaLibrary();
            //Picture picture = library.GetPictureFromToken(namePhoto);
            ////Stream stream = picture.ToString;
            //var stream = library.GetPictureFromToken(namePhoto);

            PhotoChooserTask photoChooserTask = new PhotoChooserTask();
            photoChooserTask.Completed += new EventHandler<PhotoResult>(photoChooserTask_Completed);
            photoChooserTask.Show();

            SendTweetWithMediaOptions msgMedia = new SendTweetWithMediaOptions();
            msgMedia.Status = message;
            Dictionary<string, Stream> imageDict = new Dictionary<string, Stream> { { "test", imageStream } };
            //imageDict.Add(imagePath, imageStream);
            msgMedia.Images = imageDict;
            //status = service.SendTweetWithMedia(new SendTweetWithMediaOptions() { Status = readerMsg.Message, Images = imageDict });
            service.SendTweetWithMedia(msgMedia, tweetResponse);

            ////var service = GetAuthenticatedService();
            //using (var stream = new FileStream("daniel_8bit.png", FileMode.Open))
            //{
            //    var tweet = service.SendTweetWithMedia(new SendTweetWithMediaOptions
            //        {
            //            Status = "Can_tweet_with_image:Tweet",
            //            Images = new Dictionary<string, Stream> {{"test", stream}}
            //        });
            //    //Assert.IsNotNull(tweet);
            //    //Assert.AreNotEqual(0, tweet.Id);
            //}

            //service.SendTweetWithMedia(new SendTweetWithMediaOptions
            //{
            //    Status = "Can_tweet_with_image:Tweet",
            //    Images = new Dictionary<string, Stream> { { "test", imageStream } }
            //});

        }

        private void tweetResponse(TwitterStatus tweet, TwitterResponse response)
        {
            if (response.StatusCode == HttpStatusCode.OK)
            {
                Dispatcher.BeginInvoke(() => { MessageBox.Show("Tweet posted successfully"); });
            }
            else
            {
                if (response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    saveAccessToken(null);
                    userAuthenticated = false;
                    Dispatcher.BeginInvoke(() => { MessageBox.Show("Authentication error"); });
                }
                else
                    Dispatcher.BeginInvoke(() => { MessageBox.Show("Error, please try again later"); });
            }
        }

        private void BrowserNavitaged(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            if (e.Uri.AbsoluteUri.Contains("oauth_verifier"))
            {
                var values = ParseQueryString(e.Uri.AbsoluteUri);
                string verifier = values["oauth_verifier"];
                service.GetAccessToken(requestToken, verifier, processAccessToken);
                Dispatcher.BeginInvoke(() => { Browser.Visibility = System.Windows.Visibility.Collapsed; });
            }
        }

        private void saveAccessToken(OAuthAccessToken token)
        {
            if (IsolatedStorageSettings.ApplicationSettings.Contains("accessToken"))
                IsolatedStorageSettings.ApplicationSettings["accessToken"] = token;
            else
                IsolatedStorageSettings.ApplicationSettings.Add("accessToken", token);

            IsolatedStorageSettings.ApplicationSettings.Save();
        }

        private OAuthAccessToken getAccessToken()
        {
            if (IsolatedStorageSettings.ApplicationSettings.Contains("accessToken"))
                return IsolatedStorageSettings.ApplicationSettings["accessToken"] as OAuthAccessToken;
            else
                return null;
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (Browser.Visibility == System.Windows.Visibility.Visible)
            {
                Browser.Visibility = System.Windows.Visibility.Collapsed;
                e.Cancel = true;
            }
            base.OnBackKeyPress(e);
        }

        // From Hammock.Extensions.StringExtensions.cs
        public static IDictionary<string, string> ParseQueryString(string query)
        {
            // [DC]: This method does not URL decode, and cannot handle decoded input
            if (query.StartsWith("?")) query = query.Substring(1);

            if (query.Equals(string.Empty))
            {
                return new Dictionary<string, string>();
            }

            var parts = query.Split(new[] { '&' });

            return parts.Select(
                part => part.Split(new[] { '=' })).ToDictionary(
                    pair => pair[0], pair => pair[1]
                );
        }

        private void takepicture(object sender, RoutedEventArgs e)
        {
            //PhotoChooserTask photoChooserTask = new PhotoChooserTask();
            //photoChooserTask.Completed += new EventHandler<PhotoResult>(photoChooserTask_Completed);
            //photoChooserTask.Show();
        }

        void photoChooserTask_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                var img = new BitmapImage();
                img.SetSource(e.ChosenPhoto);



                imageStream = img;
                //namePhoto = e.OriginalFileName;



                //BitmapImage image = new BitmapImage();
                //image.SetSource(e.ChosenPhoto);
                //this.img.Source = image;
            }
        }

    }
}
4

1 に答える 1

0

私は非常によく似た問題を抱えていましたが、解決策は同じなので、質問をして、しばらくして自分で解決策を見つけました。これが解決策です。Windows Phone で SendTweetWithMediaOptions を使用できない

于 2013-06-17T14:42:48.520 に答える