简体   繁体   中英

Saving a Xamarin image to file

Hi so I'm trying to save an image selected by the user to file so that i can later upload it to my mySQL database.

So I have this code:

var result = await MediaPicker.PickPhotoAsync(new MediaPickerOptions
{
    Title = "Please pick a selfie"
});

var stream = await result.OpenReadAsync();
resultImage.Source = ImageSource.FromStream(() => stream);

string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string filename = Path.Combine(path, "myfile");

using (var streamWriter = new StreamWriter(filename, true))
{
    streamWriter.WriteLine(GetImageBytes(stream).ToString());
}

using (var streamReader = new StreamReader(filename))
{
    string content = streamReader.ReadToEnd();
    System.Diagnostics.Debug.WriteLine(content);
}

Here's the GetImageBytes(..) function:

private byte[] GetImageBytes(Stream stream)
{
    byte[] ImageBytes;
    using (var memoryStream = new System.IO.MemoryStream())
    {
        stream.CopyTo(memoryStream);
        ImageBytes = memoryStream.ToArray();
    }
    return ImageBytes;
}

The code kind of works, it creates a file but doesn't save the image. Instead it saves "System.Bytes[]". It saves the name of the object, not the contents of the object.

myfile

enter image description here

Any help would be really appreciated. Thanks!

StreamWriter is for writing formatted strings, not binary data. Try this instead

File.WriteAllBytes(filename,GetImageBytes(stream));

Encode the byte array as a base64 string, then store that in the file:

private string GetImageBytesAsBase64String(Stream stream)
    {
        var imageBytes;
        using (var memoryStream = new System.IO.MemoryStream())
        {
            stream.CopyTo(memoryStream);
            imageBytes = memoryStream.ToArray();
        }
        return Convert.ToBase64String(imageBytes);
    }

If you later need to retrieve the image bytes from the file, you can use the corresponding Convert.FromBase64String(imageBytesAsBase64String) method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM