You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用CommunityToolkit MVVM将相机获取的图片流保存至PostgreSQL数据库的问题求助

CommunityToolkit MVVM将相机获取的图片流保存至PostgreSQL数据库的问题求助

大家好,我现在在做一个.NET MAUI项目,用了CommunityToolkit.MVVM做MVVM架构,想实现这么个功能:点击AvatarView上的加号按钮调用相机拍照,照片显示在AvatarView里,然后点击“Далее”按钮把这张照片存入PostgreSQL数据库。

目前拍照并显示的功能是正常的,但点击按钮后,数据库里完全没有新增图片相关的记录——其他字段(如果有的话)都能正常保存,就图片这块一直没数据。我排查了半天没找到问题,想请各位大佬帮忙看看我的代码哪里出问题了。

我的代码部分:

XAML布局(AvatarView和提交按钮)

<toolkit:AvatarView HeightRequest="400" WidthRequest="280" Background="#F9F9F9" x:Name="currenPhoto" ImageSource="{Binding Photoprofile}">
    <Grid>
        <Image Source="add.png" HeightRequest="26">
            <Image.GestureRecognizers>
                <TapGestureRecognizer Tapped="TakePhoto_Tapped"/>
            </Image.GestureRecognizers>
        </Image>
    </Grid>
</toolkit:AvatarView>

<Button Text="Далее" TextColor="White" FontSize="Body" CornerRadius="20" 
        FontAttributes="Bold" x:Name="Gotostepfor" Background="#4C25D9" 
        Clicked="Gotostepfor_Clicked" Command="{Binding AddAsyncCommand}">
    <Button.Triggers>
        <EventTrigger Event="">
            <aninmbtn:BtnAnimation/>
        </EventTrigger>
    </Button.Triggers>
</Button>

拍照的事件处理方法

private async void TakePhoto_Tapped(object sender, EventArgs e)
{
    FileResult photo = await MediaPicker.Default.CapturePhotoAsync(new MediaPickerOptions 
    { 
        Title = "Select your photo" 
    });

    if (photo != null)
    {
        var stream = await photo.OpenReadAsync();
        currenPhoto.ImageSource = ImageSource.FromStream(() => stream);
    }
}

ViewModel代码

public partial class VMSteptree : ObservableObject
{
    [ObservableProperty]
    private byte _photoprofile;

    [RelayCommand]
    public static void AddAsync()
    {
        DbMeeto dba = new();
        Auchman auchman = new() 
        { 
            Photoprofile = new() 
        };
        dba.Auchmans.Add(auchman);
    }
}

遇到的问题:

我原本以为拍照后图片流会通过绑定传到ViewModel的Photoprofile属性,然后点击按钮执行AddAsyncCommand就能把图片存进数据库,但实际运行时:

  1. 点击按钮后数据库里没有新增包含图片的记录
  2. ViewModel的Photoprofile属性看起来完全没被赋值过,一直是空的

我自己猜测可能的问题点,但不确定:

  • 是不是Photoprofile的类型错了?我设的是byte,但图片应该是字节数组byte[]?
  • 拍照的方法里我直接给currenPhoto.ImageSource赋值了,没有更新ViewModel的属性,导致绑定没生效?
  • AddAsync方法是静态的,而且没有调用数据库的SaveChangesAsync()?
  • 不知道怎么把拍照得到的Stream转换成byte[]存到ViewModel的属性里?

有没有大佬能帮我梳理一下,需要修改哪些地方才能让图片正确保存到PostgreSQL数据库里?

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.07 12:37:57