以下集合包含本地存储中的图像路径
public ObservableCollection<string> Paths;
这些文件路径由用户选择,并在Xamarin Android Player上显示如下:
/storage/emulated/0/Download/img1.jpg
/storage/emulated/0/Download/img2.jpg
现在问题出在下面-我想将这些选定的图像(基于它们的路径)转换为字节数组,以将其上传到服务器。在WPF / ASP.Net中,可以通过以下代码轻松实现:
byte[] Convert = File.ReadAllBytes("somepath...");
但是,似乎Xamarin.Forms中没有可用的东西。
我需要使用什么功能才能在Xamarin.Forms中将图像根据其在本地存储中的物理路径转换为字节数组?
----------------------------------------- -----------------------
更新
@asp_net尝试实施您的解决方案:
在我的PCL项目中,我添加了以下两个文件:
public interface IFileSystem
{
byte[] ReadAllByteS(string path);
}
和
public static class FileUtility
{
public static IFileSystem FileSystem { get; set; }
public static void SetUp(IFileSystem fs)
{
FileSystem = fs;
}
}
在Android上,我添加了以下文件:
class SharedFileSytem : IFileSystem
{
public byte[] ReadAllByteS(string path)
{
return File.ReadAllBytes(path);
}
}
而且我在初始化/注册部分有些迷路-我很确定我需要在MainActivity.cs文件中添加一些内容。
base.OnCreate(bundle);
Xamarin.Forms.Forms.Init(this, bundle);
//?
LoadApplication(new App());
因为当前,当我尝试在PCL代码中执行以下代码时
FileUtility.FileSystem.ReadAllByteS(somepath);
我收到以下错误消息:
"object reference not set to an instance of an object"
要澄清的事情:在您似乎使用的可移植类库中,System.IO不可用。但是它当然可以在“ Xamarin.Forms”中使用。
选项:
例子
在您的PCL中定义一个接口。
public interface IFileSystem
{
byte[] ReadAllByteS(string path);
}
在每个平台上(或在这种情况下,在所有平台的共享项目中)实现它。
// Could also be "IosFileSystem" or "SharedFileSytem"
public class DroidFileSystem : IFileSystem
{
public byte[] ReadAllbytes(string path)
{
return File.ReadAllBytes(path);
}
}
在您的应用启动时注册您的实现(那里有库可以帮助您)。
public static class Utils
{
public IFileSystem FileSystem { get; set; }
public static void SetUp(IFileSystem fs)
{
FileSystem = fs;
}
}
(Utils
位于您的PCL中,但其设置方法是从AppDelegate或您的主活动中调用的。)
用它:
Utils.FileSystem.ReadAllBytes(...)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句