You need to enable JavaScript to run this app. 如何将FFImageLoading调整后的图像流保存到缓存文件夹并获取路径
优惠活动
大模型
产品
解决方案
定价
更多

如何将FFImageLoading调整后的图像流保存到缓存文件夹并获取路径

FFImageLoading处理后图像流保存到缓存目录实现方案

你通过AsPNGStreamAsync()拿到的是内存流,没有对应的磁盘存储路径,无法直接调用File.Move操作,需要先将流写入到缓存目录的指定文件中,即可获取到目标路径,完整实现代码如下:

using System.IO;
// 若使用MAUI/Xamarin.Forms,需引用Microsoft.Maui.Storage获取FileSystem
// 若使用原生平台,可单独获取对应平台的缓存目录路径

var stream = await ImageService.Instance.LoadFile("icon.png")
         .DownSample(width: 200)
         .AsPNGStreamAsync();

// 构造缓存文件目标路径
string cachePath = FileSystem.CacheDirectory;
string savedImagePath = Path.Combine(cachePath, "resized_icon_200.png");
// 可自定义文件名规则,比如加入原文件哈希值避免同名覆盖

// 写入流到缓存文件
stream.Position = 0; // *必须*重置流位置,否则写入内容为空
using (var fs = new FileStream(savedImagePath, FileMode.Create, FileAccess.Write))
{
    await stream.CopyToAsync(fs);
}

// 重置流位置后再加载到ImageSource,避免显示空白
stream.Position = 0;
ImageSource myImageS= ImageSource.FromStream(() => stream);
DisplayImage.Source = myImageS;

// 此处savedImagePath就是调整后图片的缓存路径,可直接使用

注意事项

  • 如果你使用的是Xamarin原生而非MAUI/Forms,不同平台缓存目录获取方式如下:
    • iOS:NSSearchPath.GetDirectories(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomain.User, true).FirstOrDefault()
    • Android:Android.App.Application.Context.CacheDir.AbsolutePath
  • 若需要长期复用调整后的图片,可根据原文件路径、调整参数生成唯一文件名,避免重复写入浪费存储空间
  • 若你需要读取缓存中的图片直接使用,可直接通过savedImagePath调用ImageSource.FromFile(savedImagePath)加载,不需要重复处理原图

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 11:36:03