繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM