2012-06-02 3 views
2

это мой первый пост. пожалуйста, будьте добрыми :)загрузка изображения и php метод POST в windows phone

Я пытаюсь получить изображение из медиа-библиотеки (в WP 7), загрузите его с помощью httpwebrequest и сохраните его в папку на сервере. Мне удалось преобразовать изображение в строку байта (но я подозреваю, что здесь что-то не так), отправить строку с помощью POST и получить ее на моей веб-странице php.

Все, кажется, работает хорошо, но когда я преобразовываю строку байта в jpeg (используя функцию imagecreatefromstring), он всегда появляется на пустой картинке. вот мой код в C# и php. Я прошу прощения за мой английский, если он не идеален (или далеко от совершенства) :)

это мой C# код вместе с некоторыми комментариями

public partial class MainPage : PhoneApplicationPage 
{ 
    string uploadUri = @"http://192.168.138.1/meeshot/upload.php"; //php web page for retrieve and saving file in the server 
    string requestImageName = "picture"; //variable name for post ---- >$_POST['picture'] 
    string postdata; //byte data generate using BitmapToByte function 

    // Constructor 
    public MainPage() 
    { 
     InitializeComponent(); 
    } 
    PhotoChooserTask selectphoto = null; 
    Image image1 = new Image(); 
    private void button1_Click(object sender, RoutedEventArgs e) //user choosing photo from media library 
    { 
     selectphoto = new PhotoChooserTask(); 
     selectphoto.Completed += new EventHandler<PhotoResult>(selectphoto_Completed); 
     selectphoto.Show(); 
    } 
    void selectphoto_Completed(object sender, PhotoResult e) 
    { 

     if (e.TaskResult == TaskResult.OK) 
     { 

       BinaryReader reader = new BinaryReader(e.ChosenPhoto); 
       image1.Source = new BitmapImage(new Uri(e.OriginalFileName)); 

        HttpWebRequest req = HttpWebRequest.Create(
        new Uri(this.uploadUri)) as HttpWebRequest; 

        postdata = BitmapToByte(image1); //convert image to byte. My suspisicion there is something wrong here 
      req.Method = "POST"; 
      req.ContentType = "application/x-www-form-urlencoded"; 
      req.BeginGetRequestStream(HttpWebRequestButton2_RequestCallback, req); 

     } 




    } 
    private void HttpWebRequestButton2_RequestCallback(IAsyncResult result) 
    { 
     var req = result.AsyncState as HttpWebRequest; 

     using (var requestStream = req.EndGetRequestStream(result)) 
     { 
      using (StreamWriter writer = new StreamWriter(requestStream)) 
      { 
       writer.Write(requestImageName+"="+this.postdata); //writing "picture=bytedata" 
       writer.Flush(); 
      } 
     } 
     req.BeginGetResponse(HttpWebRequestButton_Callback, req); 
    } 
    private void HttpWebRequestButton_Callback(IAsyncResult result) 
    { 
     var req = result.AsyncState as HttpWebRequest; 
     var resp = req.EndGetResponse(result); 
     var strm = resp.GetResponseStream(); 
     var reader = new StreamReader(strm); 

     this.Dispatcher.BeginInvoke(() => { 
       this.DownloadedText.Text = reader.ReadToEnd(); //the web page will print byte data that has been sent using httpwebrequest. i can see that byte data has benn sent sucessfuly. 
       this.DownloadedText.Visibility = System.Windows.Visibility.Visible; 
      }); 
    }  

    private Stream ImageToStream(Image image1) 
    { 

     WriteableBitmap wb = new WriteableBitmap(400, 400); 

     wb.Render(image1, new TranslateTransform { X = 400, Y = 400 }); 

     wb.Invalidate(); 
     Stream myStream = new MemoryStream(); 

     wb.SaveJpeg(myStream, 400, 400, 0, 70); 

     return myStream; 

    } 
    private string BitmapToByte(Image image) //i suspect there is something wrong here 
    { 
     Stream photoStream = ImageToStream(image); 
     BitmapImage bimg = new BitmapImage(); 
     bimg.SetSource(photoStream); //photoStream is a stream containing data for a photo 

     byte[] bytearray = null; 
     using (MemoryStream ms = new MemoryStream()) 
     { 
      WriteableBitmap wbitmp = new WriteableBitmap(bimg); 
      wbitmp.SaveJpeg(ms, wbitmp.PixelWidth, wbitmp.PixelHeight, 0, 100); 
      ms.Seek(0, SeekOrigin.Begin); 
      bytearray = ms.GetBuffer(); 
     } 
     string str = Convert.ToBase64String(bytearray); 
     return str; 
    } 

и это мой код в веб-страницы PHP

if(isset($_REQUEST['picture'])) //check 
{ 
    $myFile = "picture.jpg"; 
    $fh = fopen($myFile, 'wb') or die("can't open file"); 
    $stringData = $_REQUEST['picture']."<br>"; 

    $im = imagecreatefromstring($stringData); 
    if ($im) { 

    imagejpeg($im); 
    fwrite($fh, $im); 
    imagedestroy($im); 
     } 
    fclose($fh); 
    echo $stringData; 
} 

ответ

Смежные вопросы