首页 > 解决方案 > 如何显示图像路径中的图像

问题描述

在此处输入图像描述我有一个问题,它不会在我的主页上显示来自我的媒体插件的图像。一旦我拍了一张照片,我就可以查看图片、转换它并将其存储为字节。无论如何,当我想将所有信息保存在一起时,图像不会加载。

private async Task TakePicture()
{
    await CrossMedia.Current.Initialize();

    if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported) //is or is not supported
    {
        await DisplayAlert(LabelCZ.AlertNoAcess,LabelCZ.AlertNoCamera,LabelCZ.AlertOk);
        return;
    }

    var imageSource = await DisplayActionSheet(LabelCZ.AlertPhoto, LabelCZ.AlertCancel, LabelCZ.AlertNewPhoto, LabelCZ.AlertGallery );

    if (imageSource == LabelCZ.AlertNewPhoto)
    {
        var imageFilename = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions()
        {
            Name = $"{DateTime.UtcNow}.jpg",
            DefaultCamera = Plugin.Media.Abstractions.CameraDevice.Rear,
            PhotoSize = PhotoSize.Medium,
            SaveToAlbum = true
        });

        if (imageFilename == null) 
            return;
        else
        {

            byte[] imageAsBytes = _cameraService.ConvertImageToBytes(imageFilename);
            var imageSourceStream = ImageSource.FromStream(() => new MemoryStream(imageAsBytes));
            AdLogEntries.Add(new AdLogEntry { ImagePath = imageFilename.AlbumPath, OriginalImage = imageAsBytes });
            PhotoListView.ItemsSource = AdLogEntries;
        }
    }
    else if (imageSource == LabelCZ.AlertGallery)
    {
        if (!CrossMedia.Current.IsPickPhotoSupported)
        {
            await DisplayAlert(LabelCZ.AlertNoAcess, LabelCZ.AlertNoCamera, LabelCZ.AlertOk);
            return;
        }

        var imageFilename = await CrossMedia.Current.PickPhotoAsync();

        if (imageFilename != null)
        {
            Photo.Source = ImageSource.FromFile(imageFilename.Path);
        }
    }
}

public byte[] ConvertImageToBytes(MediaFile imageFilename)
{
    byte[] imageAsBytes = null;

    using (var memoryStream = new MemoryStream())
    {
        imageFilename.GetStream().CopyTo(memoryStream);
        imageAsBytes = memoryStream.ToArray();
    }

    return imageAsBytes;
}

private async void Save_Clicked(object sender, EventArgs e)
{
    await SaveAdLog();
}

//TODO IsNullOR for all
//TODO Marks for required fields

private async Task SaveAdLog()
{
    if (!string.IsNullOrWhiteSpace(NameEntry.Text) || (!string.IsNullOrWhiteSpace(PriceEntry.Text) || (!string.IsNullOrWhiteSpace(LocationEntry.Text) || (!string.IsNullOrWhiteSpace(Photo.AutomationId)))))
    {
        AdLogEntry adLogEntry = new AdLogEntry
        {
            Location = LocationEntry.Text,
            Price = PriceEntry.Text,
            Name = NameEntry.Text,
            ImagePath = Photo.AutomationId,
        };

        _adService.CreateAddLogEntry(adLogEntry);

        await DisplayAlert(LabelCZ.AlertThankYou, LabelCZ.AlertSpace, LabelCZ.AlertOk);
    }
    else
    {
        await DisplayAlert(LabelCZ.AlertRequired, LabelCZ.AlertRequiredPlease, LabelCZ.AlertOk);
    };
}

XAML

<Grid Grid.Row="0" Padding="0,10,0,0">
    <ScrollView VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" >
        <Frame HasShadow="True" BackgroundColor="LightGray">
            <ListView x:Name="PhotoListView" ItemsSource="{Binding AdLogEntries}" SelectedItem="PhotoListView_OnItemSelected">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                                <StackLayout VerticalOptions="FillAndExpand">
                                    <Image Source="{Binding ImagePath}" VerticalOptions="Start" HeightRequest="100" x:Name="Photo" Grid.Row="2"/>
                                    <Image Source="{Binding OriginalImage}" VerticalOptions="Start" HeightRequest="100" Grid.Row="2"/>
                                <Label Text="{Binding ImagePath}"  />
                            </StackLayout>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </Frame>
    </ScrollView>
</Grid>

<Grid Grid.Row="1" >
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <Button x:Name="takePicturebtn" Grid.Row="0"  Style ="{StaticResource SecondaryButton}" Text="{x:Static resources:LabelCZ.ButtonTakePicture}" Clicked="TakePicture_Clicked"/>
    <Button Grid.Row="1" Style ="{StaticResource SecondaryButton}" Text="{x:Static resources:LabelCZ.ButtonTakeVideo}" Clicked="Save_Clicked"/>
</Grid>

<Grid Grid.Row="2">
    <ScrollView>
        <Grid Grid.Row="2" Padding="18,10,20,5">
            <Grid.RowDefinitions>
                <RowDefinition Height ="Auto"/>
                <RowDefinition Height ="Auto"/>
                <RowDefinition Height ="Auto"/>
                <RowDefinition Height ="Auto"/>
                    <RowDefinition Height ="Auto"/>
                </Grid.RowDefinitions>
            <Image Source="{Binding ImageName}" VerticalOptions="Start" HeightRequest="100" x:Name="Photo" Grid.Row="3"/>
            <Button  Style ="{StaticResource SecondaryButton}" Text="{x:Static resources:LabelCZ.ButtonSave}" Clicked="Save_Clicked"  Grid.Row="2"/>

            <Grid Grid.Row="0" RowSpacing="12">
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>

            <Entry  x:Name="NameEntry" Placeholder ="{x:Static resources:LabelCZ.LabelWhatAreYouSelling}" Grid.Row="1"/>
            <Picker x:Name="SectionPicker"  Grid.Row="2"  Title="{x:Static resources:LabelCZ.LabelSection}" ItemsSource="{Binding Sections}" />
            <Picker x:Name="CategoryPicker" Grid.Row="3"  Title="{x:Static resources:LabelCZ.LabelCategory}"  ItemsSource="{Binding AnimalCategories}" ItemDisplayBinding="{Binding AnimalKind}"/>
                <Picker x:Name="PetsCategoryPicker" Grid.Row="4" Title="{x:Static resources:LabelCZ.LabelPetsCategory}" ItemsSource="{Binding CatBreeds}"/>
            <Entry  x:Name="PriceEntry" Grid.Row="5" Placeholder ="{x:Static resources:LabelCZ.LabelPrice}" FontSize="{ StaticResource SubTitleSize }"/>
            <Entry  x:Name="LocationEntry" Grid.Row="6" Placeholder= "{x:Static resources:LabelCZ.LabelLocation}" FontSize="{ StaticResource SubTitleSize }" />
            <Entry x:Name="PickUpDate" Grid.Row="7" Placeholder ="{x:Static resources:LabelCZ.LabelPickUPDay}" FontSize="{ StaticResource SubTitleSize }"/>
    </Grid>

</Grid>

如果我从拍照更改这部分:

AdLogEntries.Add(new AdLogEntry { ImagePath = imageFilename.AlbumPath, OriginalImage = imageAsBytes });
PhotoListView.ItemsSource = AdLogEntries;

对此

_adService.CreateAddLogEntry(new AdLogEntry { ImagePath = imageFilename.AlbumPath, OriginalImage = imageAsBytes });
PhotoListView.ItemsSource = AdLogEntries;

然后它将根据需要在主页上显示图像,但不会与信息一起显示。它只会创建两个帖子。问题是什么?我需要他们创建一个具有特定 ID 的帖子,该帖子应该绑定到单个用户。帖子的 ID 以及用户的 ID 都是自动递增的。

标签: xamarin.forms

解决方案


利用:

MediaFile file = await CrossMedia.Current.TakePhotoAsync();

ImageSource imageSource = ImageSource.FromFile(file.Path);

正如@Leon Lu - MSFT 评论的那样。您可以将图像保存到本地存储或通过base64将图像转换为字符串,将所有信息存储到sqlite数据库。


推荐阅读