C# 将Xamarin图像保存到文件
您好,我正在尝试将用户选择的图像保存到文件中,以便稍后将其上载到我的mySQL数据库 所以我有这个代码:C# 将Xamarin图像保存到文件,c#,file,xamarin,photo,C#,File,Xamarin,Photo,您好,我正在尝试将用户选择的图像保存到文件中,以便稍后将其上载到我的mySQL数据库 所以我有这个代码: var result = await MediaPicker.PickPhotoAsync(new MediaPickerOptions { Title = "Please pick a selfie" }); var stream = await result.OpenReadAsync(); resultImage.Source = ImageSource.
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);
}
下面是GetImageBytes(..)函数:
private byte[] GetImageBytes(Stream stream)
{
byte[] ImageBytes;
using (var memoryStream = new System.IO.MemoryStream())
{
stream.CopyTo(memoryStream);
ImageBytes = memoryStream.ToArray();
}
return ImageBytes;
}
代码可以工作,它创建一个文件,但不保存图像。相反,它保存“System.Bytes[]”。它保存对象的名称,而不是对象的内容
任何帮助都将不胜感激。谢谢 将字节数组编码为base64字符串,然后将其存储在文件中:
private string GetImageBytesAsBase64String(Stream stream)
{
var imageBytes;
using (var memoryStream = new System.IO.MemoryStream())
{
stream.CopyTo(memoryStream);
imageBytes = memoryStream.ToArray();
}
return Convert.ToBase64String(imageBytes);
}
如果以后需要从文件中检索图像字节,可以使用相应的Convert.FromBase64String(imageBytesAsBase64String)方法。
StreamWriter
用于写入格式化字符串,而不是二进制数据。试试这个
File.WriteAllBytes(filename,GetImageBytes(stream));
成功了!多谢各位