[英]C# How to save an images to SD card?
我正在為Android使用Xamarin。 我加載圖像並將其放入ImageView,然后編輯圖像。 接下來,我要將圖像保存到SD卡。
任何人都知道如何將圖像保存到SD卡,因為我只能在Java Android中找到它。 我已經嘗試將代碼從Java轉換為C#,但仍然出現錯誤。
任何幫助,在此先感謝。
我在InputStream iS = Resources.OpenRawResource(Resource.Drawable.Icon);
遇到錯誤InputStream iS = Resources.OpenRawResource(Resource.Drawable.Icon);
因為錯誤是“無法將類型'System.IO.Stream'隱式轉換為'Java.IO.InputStream'”
這是代碼:
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) {
// ...
}
我用它來將捕獲的照片保存到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);
}
}
找到了答案,歸功於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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.