我做了研究并且依赖于这个解决方案:http://forums.xamarin.com/discussion/22682/is-there-a-way-to-turn-an-imagesource-into-a-byte-array
最初的问题:http://forums.xamarin.com/discussion/29569/is-there-a-cross-platform-solution-to-imagesource-to-byte#latest
我们想通过HTTP Post上传图片,这是我们尝试的内容:
HttpClient httpClient = new HttpClient ();
byte[] TargetImageByte = **TargetImageSource**; //How to convert it to a byte[]?
HttpContent httpContent = new ByteArrayContent (TargetImageByte);
httpClient.PostAsync ("https://api.magikweb.ca/debug/file.php", httpContent);
Run Code Online (Sandbox Code Playgroud)
我们也很难使用我们必须包含在使用条款中的库.它似乎using System.IO;
有效,但它不会让我们访问类似FileInfo
或FileStream
.
除了自定义平台特定的转换器之外,任何人都知道如何做到这一点?可能是一个Xamarin.Forms.ImageSource函数toByte()?
Lemme知道您是否需要更多信息.
TargetImageSource
是一个Xamarin.Forms.ImageSource
.
ImageSource TargetImageSource = null;
解决方案(Sten是对的)
的ImageSource
具有从另一种类型的始发存在,这就先前类型可以转换为一个byte[]
.在这种情况下,我用的是Xamarin.Forms.Labs拍照,它返回一个MediaFile
在其中FileStream
是通过访问Source
属性.
//--Upload image
//Initialization
HttpClient httpClient = new HttpClient ();
MultipartFormDataContent formContent = new MultipartFormDataContent ();
//Convert the Stream into byte[]
byte[] TargetImageByte = ReadFully(mediaFile.Source);
HttpContent httpContent = new ByteArrayContent (TargetImageByte);
formContent.Add (httpContent, "image", "image.jpg");
//Send it!
await httpClient.PostAsync ("https://api.magikweb.ca/xxx.php", formContent);
App.RootPage.NavigateTo (new ClaimHistoryPage());
Run Code Online (Sandbox Code Playgroud)
功能:
public static byte[] ReadFully(Stream input)
{
using (MemoryStream ms = new MemoryStream()){
input.CopyTo(ms);
return ms.ToArray();
}
}
Run Code Online (Sandbox Code Playgroud)
我觉得你有点倒退了.
ImageSource
是一种为Xamarin.Forms.Image提供源图像以显示某些内容的方法.如果您已经在屏幕上显示某些内容,那么您的Image
视图将填充来自其他地方的数据,例如文件或资源,或者存储在内存中的数组中......或者您首先获得该数据.ImageSource
您可以保留对它的引用并根据需要上传它,而不是尝试从您那里获取数据.
如果您认为此解决方案不适用于您的情况,也许您可以详细说明您的特殊需求.
伪代码:
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);
}
Run Code Online (Sandbox Code Playgroud)
更新:
由于您正在拍照,您可以将MediaFile.Source
流复制到内存流中,然后您可以将内存流的位置重置为指向流的开头,以便您可以再次读取它并将其复制到http正文.
或者,您可以将其存储MediaFile.Source
到文件中并用于ImageSource.FromFile
在UI中加载它,并在必要时 - 您可以将文件的内容复制到http帖子正文中.
归档时间: |
|
查看次数: |
11602 次 |
最近记录: |