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

Maui中ImageSource.FromStream始终为null?运行时更新图片源遇问题

MAUI运行时更新ImageSource问题解决

问题核心在于MemoryStream的生命周期管理:你用using块包裹了流,当using执行完毕后流会被自动释放,但ImageSource.FromStream的回调是延迟执行的——等MAUI真正去读取流的时候,流已经不存在了,导致图片加载失败,最终Source为null。

同时要注意:eventArgs.Frame.Save执行后,流的位置会停在末尾,若不重置位置,即使流没被释放,也读不到任何内容。

修复方案1:保存字节数组(推荐)

把流内容转成字节数组保存,避免using块释放流的影响,每次回调触发时基于字节数组创建新流:

byte[] imageBytes;
using (MemoryStream stream = new MemoryStream())
{
    eventArgs.Frame.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
    imageBytes = stream.ToArray();
}
MainThread.BeginInvokeOnMainThread(() => 
{
    this.camcap.Source = ImageSource.FromStream(() => new MemoryStream(imageBytes));
});

修复方案2:手动管理流生命周期

去掉using块,在回调里返回流的副本,确保原流不会被意外释放:

MemoryStream stream = new MemoryStream();
eventArgs.Frame.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
stream.Position = 0; // 重置流位置到起始处
MainThread.BeginInvokeOnMainThread(() => 
{
    this.camcap.Source = ImageSource.FromStream(() => 
    {
        var copyStream = new MemoryStream();
        stream.CopyTo(copyStream);
        copyStream.Position = 0;
        return copyStream;
    });
});

内容的提问来源于stack exchange,提问作者Gregory

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 23:07:33