【问题标题】:How to add a bitmap to a specific album in the gallery?如何将位图添加到图库中的特定相册?
【发布时间】:2019-09-11 19:24:28
【问题描述】:

我尝试了很多方法,但都没有奏效。我想创建一个特定的相册并将位图保存到那里的 JPEG 中。

我使用 Xamarin。我该怎么办?

【问题讨论】:

标签: java c# xamarin bitmap gallery


【解决方案1】:

我写了一个关于它的演示。

我在资源文件夹中放了一张图片,然后我会读到位图

 btnSelectImage = (Button)FindViewById(Resource.Id.btnSelectImage);
        Bitmap bitmap = BitmapFactory.DecodeResource(this.ApplicationContext.Resources , Resource.Drawable.splashlogo);
        btnSelectImage.Click += (o, e) =>
        {
            saveImageToGally(bitmap, this);
        };

然后将其发送到图库中的特定相册。

有代码。

public void saveImageToGally(Bitmap finalBitmap,Context context)
    {
        //create a directory called MyCamera
        string root = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDcim).ToString() + "/MyCamera/";

       //create the Directory
        System.IO.Directory.CreateDirectory(root);

        File myDir = new File(root);
        myDir.Mkdir();
        //Image name
        string fname = "Image-" + "Image1" + ".png";
        File file = new File(myDir, fname);
        Log.Error("FilePath", file.AbsolutePath);

        if (file.Exists()) file.Delete();
        Log.Error("FilePath", root + fname);
        //total path
        string path = root + fname;

        try
        {


            var fs = new System.IO.FileStream(path, System.IO.FileMode.OpenOrCreate);
            if (fs != null)
            {
                finalBitmap.Compress(Bitmap.CompressFormat.Png, 90, fs);
                fs.Close();
            }

        }
        catch (Exception e)
        {
            e.PrintStackTrace();

        }

        MediaScannerConnection.ScanFile(context, new string[] { file.Path }, new string[] { "image/jpeg" }, null);

    }

请不要忘记添加以下权限。

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

【讨论】:

    【解决方案2】:

    请注意,您应该在运行时授予外部存储权限,因为它们是关键权限!

    您可以阅读更多here

    【讨论】:

    • 这实际上解决了我与其他答案的问题.. 谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    • 2010-11-04
    • 2012-03-04
    相关资源
    最近更新 更多