I'm using Xamarin for Android. I load an image and put it in ImageView, then I edit the image. Next I want to save that image to SD card.
Anyone know how to save the image into SD card because I only can find it in Java Android. I already try to convert the code from Java to C# but still get an error.
Any help, thanks in advance.
I get an error at InputStream iS = Resources.OpenRawResource(Resource.Drawable.Icon);
as the error is "cannot implicitly convert type 'System.IO.Stream' to 'Java.IO.InputStream'"
Here's the code:
Java.IO.File path = Android.OS.Environment.GetExternalStoragePublicDirectory (Android.OS.Environment.DirectoryPictures);
Java.IO.File file = new Java.IO.File (path, "Icon.png");
try {
path.Mkdirs();
InputStream iS = Resources.OpenRawResource(Resource.Drawable.Icon);
OutputStream oS = new FileOutputStream(file);
byte[] data = new byte[iS.Available()];
iS.Read(data);
oS.Write(data);
iS.Close();
oS.Close();
} catch (Exception ex) {
// ...
}
I use this to save the captured photo to sdcard:
public void OnPictureTaken(byte[] data, Android.Hardware.Camera camera)
{
// Save the image JPEG data to the SD card
FileOutputStream outStream = null;
File dataDir = Android.OS.Environment.ExternalStorageDirectory;
if (data!=null)
{
try
{
outStream = new FileOutputStream(dataDir + "/" + PICTURE_FILENAME);
outStream.Write(data);
outStream.Close();
}
catch (FileNotFoundException e)
{
Android.Util.Log.Debug("SIMPLECAMERA", e.Message);
}
catch (IOException e)
{
Android.Util.Log.Debug("SIMPLECAMERA", e.Message);
}
File file = new File(dataDir + "/" + PICTURE_FILENAME);
try
{
ExifInterface exif = new ExifInterface(file.CanonicalPath);
// Read the camera model and location attributes
exif.GetAttribute(ExifInterface.TagModel);
float[] latLng = new float[2];
exif.GetLatLong(latLng);
// Set the camera make
exif.SetAttribute(ExifInterface.TagMake, “My Phone”);
exif.SetAttribute(ExifInterface.TagDatetime,
System.DateTime.Now.ToString());
}
catch (IOException e) {
Android.Util.Log.Debug("SIMPLECAMERA", e.Message);
}
}
else
{
Toast.MakeText(this, "No Image Captured", ToastLength.Long);
}
}
found the answer, credit to Mohd Riyaz.
var yourImageView = new ImageView(this); //Your image view
var fetchedDrawable = yourImageView.Drawable;
BitmapDrawable bitmapDrawable = (BitmapDrawable)fetchedDrawable;
var bitmap = bitmapDrawable.Bitmap;
using (var stream = new FileStream("AbsolutePath_File", FileMode.Create))
{
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.