【问题标题】:Xamarin Forms convert ImageSource to actual png image and store on deviceXamarin Forms 将 ImageSource 转换为实际的 png 图像并存储在设备上
【发布时间】:2017-10-07 17:12:13
【问题描述】:

有没有办法将 ImageSource(从 api 调用中提取)转换为设备上的实际 png 文件,然后在需要时将其作为 FileImageSource 访问?我想实现图像的缓存,以便我的应用程序不依赖于网络。

【问题讨论】:

  • FFImageLoading 包会为你做这件事。如果您确实需要自己做,那么在加载之后但在将其分配给图像源之前将其缓存起来会更有效率。

标签: c# xamarin xamarin.forms


【解决方案1】:

iOS

NSData imgData = null;
var renderer = new Xamarin.Forms.Platform.iOS.StreamImagesourceHandler ();
UIKit.UIImage photo = await renderer.LoadImageAsync (img);

var savedImageFilename = System.IO.Path.Combine (directory, filename);
NSFileManager.DefaultManager.CreateDirectory(directory, true, null);

if (System.IO.Path.GetExtension (filename).ToLower () == ".png")
    imgData = photo.AsPNG ();
else
    imgData = photo.AsJPEG (100);

NSError err = null;
imgData.Save (savedImageFilename, NSDataWritingOptions.Atomic, out err)

安卓

System.IO.Stream outputStream = null;

var renderer = new Xamarin.Forms.Platform.Android.StreamImagesourceHandler ();
Bitmap photo = await renderer.LoadImageAsync (img, Forms.Context);
var savedImageFilename = System.IO.Path.Combine (directory, filename);

System.IO.Directory.CreateDirectory(directory);

bool success = false;
using (outputStream = new System.IO.FileStream(savedImageFilename, System.IO.FileMode.Create))
{
    if (System.IO.Path.GetExtension (filename).ToLower () == ".png")
        success = await photo.CompressAsync(Bitmap.CompressFormat.Png, 100, outputStream);
    else
        success = await photo.CompressAsync(Bitmap.CompressFormat.Jpeg, 100, outputStream);
}

您可能希望将其声明为在公共项目中抽象并在每个平台中实现的依赖服务,其方法如下:

Task<bool> SaveImage(string directory, string filename, ImageSource img);

【讨论】:

    猜你喜欢
    • 2018-12-27
    • 2020-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-22
    相关资源
    最近更新 更多