How to convert image from Plugin.Media to Base64?

Hello,
I have an issue with my need to upload an image to my web server.

I'm using Plugin.Media from James Montemagno. I use this code to let the user select an image.

var media = CrossMedia.Current;
var file = await media.PickPhotoAsync();

Then, I have to convert that "file" to base64 to upload it to my web server, but I don't know how to do that since in PCL there's no System.IO.File.

How can I do that? Do you have any hint?
Thanks!

Best Answers

  • JoeMankeJoeManke US ✭✭✭✭✭
    Accepted Answer

    Sorry, it should be stream.ReadAsync, not WriteAsync.

Answers

  • ClintStLaurentClintStLaurent USUniversity ✭✭✭✭✭

    I think the NuGet package 'Shim' provides a number of stubs for missing namespaces, including System.IO.File

  • FrancescoCremaFrancescoCrema USMember ✭✭

    @JoeManke said:
    You could do something like this:

    var stream = file.GetStream();
    var bytes = new byte [stream.Length];
    await stream.WriteAsync(bytes, 0, (int)stream.Length);
    string base64 = System.Convert.ToBase64String(bytes);
    

    I get this error:

    System.NotSupportedException: This stream does not support writing

    I will try with Shim

  • JoeMankeJoeManke USMember ✭✭✭✭✭
    Accepted Answer

    Sorry, it should be stream.ReadAsync, not WriteAsync.

  • FrancescoCremaFrancescoCrema USMember ✭✭

    @JoeManke said:
    Sorry, it should be stream.ReadAsync, not WriteAsync.

    Yes got it, thank you!

  • serkan_CAKMAKserkan_CAKMAK USMember ✭✭

    wow it help me so much thank you guys specialy @JoeManke

  • EmanEman USMember

    Hi,

    I tried the solution above, but when I copy the string value to an online base64-to-image-converter, the image is cropped, only the top part of the image is rendered and not the whole image. Am I missing something? I tried it on iOS device.

Sign In or Register to comment.