C#如何将图像保存到SD卡?

时间:2015-02-18 08:13:10

标签: c# android image xamarin

我正在使用Xamarin for Android。我加载一个图像并将其放入ImageView,然后我编辑图像。接下来我想将该图像保存到SD卡。

任何人都知道如何将图像保存到SD卡中,因为我只能在Java Android中找到它。我已经尝试将代码从Java转换为C#但仍然出错。

任何帮助,提前谢谢。


我在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) {
    // ...
}

2 个答案:

答案 0 :(得分:3)

我用这个将拍摄的照片保存到SD卡:

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

答案 1 :(得分:-1)

找到答案,归功于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);
        }