Is there a cross-platform solution to ImageSource to byte[]?

后端 未结 1 358
一个人的身影
一个人的身影 2020-12-06 05:52

I did researches and fell on this solution: http://forums.xamarin.com/discussion/22682/is-there-a-way-to-turn-an-imagesource-into-a-byte-array

Initial question: http

相关标签:
1条回答
  • 2020-12-06 06:33

    I think you're looking at it a bit backwards.

    ImageSource is a way to provide a source image for Xamarin.Forms.Image to show some content. If you're already showing something on the screen your Image view was populated with data that came from elsewhere, such as a file or resource or stored in an array in memory... or however else you got that in the first place. Instead of trying to get that data back from ImageSource you can keep a reference to it and upload it as needed.

    Maybe you can elaborate a bit on your particular need if you don't feel this solution applies to your case.

    Pseudo code:

    ShowImage(){
      ImageSource imageSource = ImageSource.FromFile("image.png"); // read an image file
      xf_Image.Source = imageSource; // show it in your UI
    }
    
    UploadImage(){
      byte[] data =  File.ReadAll("image.png");
      // rather than 
      // byte[] data = SomeMagicalMethod(xf_Image.Source);
      HttpClient.Post(url, data);
    }
    

    UPDATE:

    Since you're taking a picture you can copy the MediaFile.Source stream into a memory stream, then you can reset the memory stream's position to point at the beginning of the stream so that you can read it once again and copy it to the http body.

    Alternatively you can store the MediaFile.Source to a file and use ImageSource.FromFile to load it in the UI, and when necessary - you can copy the file's contents into an http post body.

    0 讨论(0)
提交回复
热议问题