Like Jason mentioned in the comments you can extend your code in the platform project by adding a File.WriteAllBytes();
line and save your file from right there.
Or you can decouple it and create another DependencyService. For instance create the IScreenshotService
like: DependencyService.Get<IScreenshotService>().SaveScreenshot("MyScreenshot123", ScreenShot);
And create implementations like this:
PCL
public interface IScreenshotService
{
SaveScreenshot(string filename, byte[] imageBytes);`
}
iOS
[assembly: Xamarin.Forms.Dependency(typeof(ScreenshotService_iOS))]
namespace YourApp.iOS
{
public class ScreenshotService_iOS: IScreenshotService
{
public void SaveScreenshot(string filename, byte[] imageBytes)
{
var screenshot = new UIImage(NSData.FromArray(imageBytes));
screenshot.SaveToPhotosAlbum((image, error) =>
{
// Catch any error here
if(error != null)
Console.WriteLine(error.ToString());
// If you want you can access the image here from the image parameter
});
}
}
}
Android
[assembly: Xamarin.Forms.Dependency(typeof(Picture_Droid))]
namespace YourApp.Droid
{
public class ScreenshotService_Android : IScreenshotService
{
public void SaveScreenshot(string filename, byte[] imageBytes)
{
var dir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDcim);
var pictures = dir.AbsolutePath;
// You might want to add a unique id like GUID or timestamp to the filename, else you could be overwriting an older image
string filePath = System.IO.Path.Combine(pictures, filename);
try
{
// Write the image
File.WriteAllBytes(filePath, imageData);
// With this we add the image to the image library on the device
var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
mediaScanIntent.SetData(Uri.FromFile(new File(filePath)));
Xamarin.Forms.Forms.Context.SendBroadcast(mediaScanIntent);
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
Don't forget to add the appropriate permissions on the Android app (probably WRITE_EXTERNAL_STORAGE is enough)
Lastly you could look at third-party libraries like Splat for example.