问题
Is there a way to save the picture in an image control to the Android gallery in Xamarin Forms? All help is appreciated.
var image = new Image();
image.Source = "test.png";
Screenshot
回答1:
You could use Dependency Service
to get the stream from Resource/drawable
image.
Create the IDependency interface.
public interface IDependency
{
MemoryStream DrawableByNameToByteArray(string fileName);
}
Android implementation
public class DependencyImplementation : IDependency
{
public MemoryStream DrawableByNameToByteArray(string fileName)
{
var context = Application.Context;
using (var drawable = Xamarin.Forms.Platform.Android.ResourceManager.GetDrawable(context, fileName))
using (var bitmap = ((BitmapDrawable)drawable).Bitmap)
{
var stream = new MemoryStream();
bitmap.Compress(Bitmap.CompressFormat.Png, 100, stream);
bitmap.Recycle();
return stream;
}
}
}
For the IOS implementation, you could refer to the thread in SO. Convert Image (from drawable folder) to ByteArray
And then register in Android Mainactivity.
DependencyService.Register<IDependency, DependencyImplementation>();
If your android version is highter than android 6.0, you need runtime permission for storage in this question. Please check the Plugin.Permissions
with runtime permission.
https://github.com/jamesmontemagno/PermissionsPlugin
After that, you could save the image to picture internal storage.
var filename = "";
var source = image.Source as FileImageSource;
if (source != null)
{
filename = source.File;
}
var savingFile = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyPictures);
//var savingFile1 = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData), "save.png");
var S = DependencyService.Get<IDependency>().DrawableByNameToByteArray(filename);
if (!File.Exists(savingFile))
{
File.WriteAllBytes(savingFile, S.ToArray());
}
In Internal Storage, you couldn't see the files without root permission. If you want to view it, you could use adb tool. Please check the way in link. How to write the username in a local txt file when login success and check on file for next login?
回答2:
You can use Media Plugin and it can solve your issue. https://github.com/jamesmontemagno/MediaPlugin
You can visit the above link.
takePhoto.Clicked += async (sender, args) =>
{
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
DisplayAlert("No Camera", ":( No camera available.", "OK");
return;
}
var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
Directory = "Sample",
Name = "test.jpg"
});
if (file == null)
return;
await DisplayAlert("File Location", file.Path, "OK");
image.Source = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
return stream;
});
};
来源:https://stackoverflow.com/questions/58667328/save-image-from-an-image-box-to-gallery-in-xamarin-forms