首页 > 解决方案 > 上传后从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` 对象,而不是我期望的字符串。

还有其他方法可以获取上传图像的名称吗?

标签: c#imagexamarinxamarin.forms

解决方案


如果您确定 ImageSource 是流,则可以使用将 ImageSource 转换为 StreamImageSource,然后从中获取流。

例子:

var imageStreamSource = (StreamImageSource)profilePicture.Source;
Stream actualStream = await imageStreamSource.Stream(new CancellationToken());

推荐阅读