上传后从图像获取图像源

问题描述 投票:0回答:1

我目前正在逐步讲解如何从手机的图片库link here中上传图片,以允许用户将图片上传到我的应用程序中,并将其设置为个人资料图片。我可以从手机的图库中获取图像,但是当我尝试保存时,无法从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# image xamarin xamarin.forms
1个回答
0
投票

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

示例:

var imageStreamSource = (StreamImageSource)profilePicture.Source;
Stream actualStream = await imageStreamSource.Stream(new CancellationToken());
© www.soinside.com 2019 - 2024. All rights reserved.