C# 上传后从图像中获取图像源
我目前正在学习如何从手机的照片库上传图像,以允许用户将图像上传到我的应用程序中,并将其设置为个人资料图片。我可以从手机的多媒体资料中获取图像,但是当我尝试保存时,无法从xaml中检索图像源 下面是图像的xaml和用户单击以上载图像的按钮C# 上传后从图像中获取图像源,c#,image,xamarin,xamarin.forms,C#,Image,Xamarin,Xamarin.forms,我目前正在学习如何从手机的照片库上传图像,以允许用户将图像上传到我的应用程序中,并将其设置为个人资料图片。我可以从手机的多媒体资料中获取图像,但是当我尝试保存时,无法从xaml中检索图像源 下面是图像的xaml和用户单击以上载图像的按钮 <Button Text="Pick a Profile Image" Clicked="OnPictureButton_Clicked"
<Button Text="Pick a Profile Image"
Clicked="OnPictureButton_Clicked"
Grid.Column="0"></Button>
<Image Source="{Binding Employee.ProfilePicture}"
Grid.Column="1"
x:Name="profilePicture"
Grid.RowSpan="2"
WidthRequest="200"></Image>
下面是相应的c代码:
private async void OnPictureButton_Clicked(object sender, EventArgs e)
{
(sender as Button).IsEnabled = false;
// _stream is a private global variable
// Allow the user to view images on the phone
_stream = await DependencyService.Get<IPhotoPickerService>().GetImageStreamASync();
// If they select an image, set it as the source for profilePicture
if (_stream != null)
{
profilePicture.Source = ImageSource.FromStream(() => _stream);
}
(sender as Button).IsEnabled = true;
}
private async void Clicked_EmployeeSaved(object sender, EventArgs e)
{
var data = (EmployeeFull)BindingContext;
var uploadedPicture = profilePicture.Source; // Should be uploaded image
// Testing how to get the source for the image (Can disregard for question)
Bitmap bitmap = BitmapFactory.DecodeStream(_stream);
MemoryStream ms = new MemoryStream();
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, ms);
byte[] byteArray;
byteArray = ms.ToArray();
}
现在,我知道,一旦用户从他们设备上的图库中选择了一个图像,流就会关闭,因此我将无法在代码中稍后访问它,就像我在显示的第二个函数中尝试的那样
但是,我无法检索已选择上载的图像的名称。在屏幕上,用户可以看到此图像,因为我已将所选图像设置为profilePicture标记的源,但当我尝试在用户单击“保存”时获取该源时,它会显示一个ImageSource“对象”,而不是我期望的字符串
是否有其他方法可以获取上传图像的名称 如果您确定ImageSource是一个流,您可以使用cast ImageSource来StreamImageSource,然后从中获取流 例如:
var imageStreamSource = (StreamImageSource)profilePicture.Source;
Stream actualStream = await imageStreamSource.Stream(new CancellationToken());
当用户选择所选图像时,您需要保存对该图像的引用,并在以后重新使用该引用。@Jason我确实看到了。因此,保存对memoryStream的引用,并在第二种方法中访问它,例如memoryStream ms=new memoryStream;`_stream.CopyToms;`?或者将流中的字节[]保存到内存中。或者将其写入文件。@Jason,那么如何在第二个函数中检索该值?请使用类级别变量