【问题标题】:How do i save an image to the gallery using an app i made?如何使用我制作的应用程序将图像保存到图库?
【发布时间】:2019-04-01 09:15:18
【问题描述】:

我有这个 Xamarin Android 应用程序(不是 Forms),它可以打开相机并让我拍照并随身携带或拍摄新照片。之后,ImageView 使用位图向我展示了应用程序上的图片。我无法使用位图保存到画廊(我不知道如何,或者是否有更简单的方法)。我需要应用程序来获取应用程序拍摄的最后一张照片(为什么需要保存它)并通过单击按钮将其发送到服务器(我也需要一些帮助)。这就是我需要做的。 这里是代码MainActivity.cs

using Android.App;

using Android.Widget;

using Android.OS;

using Android.Content;

using Android.Provider;

using Android.Runtime;

using Android.Graphics;

namespace CameraApp

{

    [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]

    public class MainActivity : Activity

    {

        ImageView imageView;

        protected override void OnCreate(Bundle bundle)

        {

            base.OnCreate(bundle);

            SetContentView(Resource.Layout.activity_main);

            Button btnCamera = FindViewById<Button>(Resource.Id.btnCamera);

            imageView = FindViewById<ImageView>(Resource.Id.imageView);

            btnCamera.Click += BtnCamera_Click;

        }

        protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)

        {

            base.OnActivityResult(requestCode, resultCode, data);

            Bitmap bitmap = (Bitmap)data.Extras.Get("data");

            imageView.SetImageBitmap(bitmap);

        }

        private void BtnCamera_Click(object sender, System.EventArgs e)

        {

            Intent intent = new Intent(MediaStore.ActionImageCapture);

            StartActivityForResult(intent, 0);

        }

    }

}

【问题讨论】:

标签: c# android xamarin


【解决方案1】:

我写了一个关于你的需求的演示。我添加了相机和外部存储权限并将图像存储到画廊,这里是运行 GIF。

有运行demo的代码。我添加了运行时权限(相机和WriteExternalStorage)请求。判断用户没有拍照的情况,然后返回应用程序。

[Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
public class MainActivity : AppCompatActivity, ActivityCompat.IOnRequestPermissionsResultCallback
{
    Button button1;
    ImageView imageView1;
    View layout;
    static readonly int REQUEST_CAMERA_WriteExternalStorage = 0;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.activity_main);
        layout = FindViewById<RelativeLayout>(Resource.Id.sample_main_layout);
        button1 = FindViewById<Button>(Resource.Id.button1);
        imageView1 = FindViewById<ImageView>(Resource.Id.imageView1);
        button1.Click += (o, e) =>
        {
            CheckPermission();
        };
    }


    public  void CheckPermission()
    {
        if ((ContextCompat.CheckSelfPermission(this, Manifest.Permission.Camera) == (int)Permission.Granted)&& (ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) == (int)Permission.Granted))
        {
            // Camera and store permission has  been granted
            ShowCamera();
        }
        else
        {
            // Camera and store permission has not been granted
            RequestPermission();

        }


    }

    private void RequestPermission()
    {

        ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.Camera, Manifest.Permission.WriteExternalStorage }, REQUEST_CAMERA_WriteExternalStorage);

    }


    //get result of persmissions
    public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults)
    {
        if (requestCode == REQUEST_CAMERA_WriteExternalStorage)
        {


            if ( PermissionUtil.VerifyPermissions(grantResults))
            {
                // All required permissions have been granted, display Camera.

                ShowCamera();
            }
            else
            {
                // permissions did not grant, push up a snackbar to notificate USERS
                Snackbar.Make(layout, Resource.String.permissions_not_granted, Snackbar.LengthShort).Show();
            }

        }
        else
        {
            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    private void ShowCamera()
    {
        Intent intent = new Intent(MediaStore.ActionImageCapture);
        StartActivityForResult(intent, 0);
    }


    protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
    {
        base.OnActivityResult(requestCode, resultCode, data);
        Bitmap bitmap=null;
        //If user did not take a photeo , he will get result of bitmap, it is null
        try {
             bitmap = (Bitmap)data.Extras.Get("data");
        } catch(Exception e)
        {
            Log.Error("TakePhotoDemo1", e.Message);
            Toast.MakeText(this, "You did not take a photo", ToastLength.Short).Show();

        }

        if (bitmap != null)
        {
            MediaStore.Images.Media.InsertImage(ContentResolver, bitmap, "screen", "shot");
            imageView1.SetImageBitmap(bitmap);
        }
        else
        {
            Toast.MakeText(this, "You did not take a photo", ToastLength.Short).Show();
        }

    }

}

PermissionUtil.cs通过验证给定数组中的每个条目的值是否为 Permission.Granted 来检查所有给定的权限是否已被授予。

   public abstract class PermissionUtil
{

    public static bool VerifyPermissions(Permission[] grantResults)
    {
        // At least one result must be checked.
        if (grantResults.Length < 1)
            return false;

        // Verify that each required permission has been granted, otherwise return false.
        foreach (Permission result in grantResults)
        {
            if (result != Permission.Granted)
            {
                return false;
            }
        }
        return true;
    }
}

这是我的代码。

https://github.com/851265601/TakePhotoDemo1

之前的代码会将图片添加到图库末尾(MediaStore.Images.Media.InsertImage)。如果您想修改日期以使其出现在开头或任何其他元数据中,请参阅此链接。 https://gist.github.com/samkirton/0242ba81d7ca00b475b9

【讨论】:

  • 您有任何更新吗?如果回复对您有帮助,请将回复标记为答案。
  • Leon Lu 非常感谢。我现在明白了如何做到这一点,我很欣赏代码示例。但我有一个问题。您添加了联系人字符串,但我不知道您使用它们的目的。再次感谢您
【解决方案2】:

可以通过MediaStore插入图片

MediaStore.Images.Media.InsertImage(this, yourBitmap, yourTitle, yourDescription);

注意:您可能需要为此添加写入外部存储权限。

【讨论】:

    猜你喜欢
    • 2016-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-25
    • 1970-01-01
    • 1970-01-01
    • 2014-10-16
    • 1970-01-01
    相关资源
    最近更新 更多