MassiveMelon
MassiveMelon

Reputation: 25

Xamarin Forms convert ImageSource to actual png image and store on device

Is there a way to convert a ImageSource (pulled from api call) into an actual png file on the device and then access it later as a FileImageSource when it is needed? I would like to implement caching of the images so that my application is not as network dependent.

Upvotes: 2

Views: 3928

Answers (1)

Alirio Mendes
Alirio Mendes

Reputation: 819

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)

Android

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);
}

Probably you will want to declare it as a Dependency Service abstracted in the common project and implemented in each platform, which would have a method like:

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

Upvotes: 4

Related Questions