c# - 上传后从Image中获取图片源
问题描述
我目前正在逐步了解如何从手机的照片库链接上传图片,以允许用户将图片上传到我的应用程序,他们可以将其设置为他们的个人资料图片。我可以从手机的图库中获取图像,但是当我尝试保存时,我无法从xaml
.
下面是xaml
图片和用户单击以上传图片的按钮。
<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 是流,则可以使用将 ImageSource 转换为 StreamImageSource,然后从中获取流。
例子:
var imageStreamSource = (StreamImageSource)profilePicture.Source;
Stream actualStream = await imageStreamSource.Stream(new CancellationToken());
推荐阅读
- javascript - 循环遍历对象数组并使用 Javascript 在 HTML 中一次仅显示对象属性
- python - 如何将数据从 csv 文件导入和导出到 HTML?
- node.js - 使用 Node.js 和 MongoDB 限制返回的文档
- r - 要替换的项目数不是替换长度错误的倍数
- javascript - 使用 function-plot.js 绘制指数函数
- java - 在Java中将父类转换为子类
- c# - 是否可以在一定天数后删除特定的 blob?Azure Blob 存储
- php - Content-Encoding 标头通过转发代理消失
- c - 检查字符串在 C 中是否为给定格式
- javascript - 错误处理响应:TypeError: Cannot read property 'show' of undefined at chrome-extension