我做了一些研究,并研究了这个解决方案: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上传一个图像,下面是我们尝试过的:
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);我们在使用子句中必须包括的库方面也遇到了困难。using System.IO;看起来很有效,但它不能让我们访问像FileInfo或FileStream这样的类。
除了定制的平台专用转换器之外,还有人知道如何做到这一点吗?可能是Xamarin.Forms.ImageSource函数toByte()吗?
如果你需要更多的信息请告诉我。
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());职能:
public static byte[] ReadFully(Stream input)
{
using (MemoryStream ms = new MemoryStream()){
input.CopyTo(ms);
return ms.ToArray();
}
}发布于 2014-12-17 18:59:50
我觉得你看上去有点颠倒了。
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);
}更新:
由于您正在拍照,您可以将MediaFile.Source流复制到内存流中,然后可以将内存流的位置重置为指向流的开头,以便您可以再次读取它并将其复制到http。
或者,您可以将MediaFile.Source存储到文件中,并使用ImageSource.FromFile将其加载到UI中,并在必要时--您可以将文件的内容复制到http正文中。
https://stackoverflow.com/questions/27532462
复制相似问题