猿问

如何将位图添加到图库中的特定相册?

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

我使用 Xamarin。我该怎么办?


慕标琳琳
浏览 130回答 2
2回答

小怪兽爱吃肉

我写了一个关于它的演示。我将图片放在资源文件夹中,然后将其读取为位图&nbsp;btnSelectImage = (Button)FindViewById(Resource.Id.btnSelectImage);&nbsp; &nbsp; &nbsp; &nbsp; Bitmap bitmap = BitmapFactory.DecodeResource(this.ApplicationContext.Resources , Resource.Drawable.splashlogo);&nbsp; &nbsp; &nbsp; &nbsp; btnSelectImage.Click += (o, e) =>&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; saveImageToGally(bitmap, this);&nbsp; &nbsp; &nbsp; &nbsp; };然后将其发送到图库中的特定相册。有代码。public void saveImageToGally(Bitmap finalBitmap,Context context)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; //create a directory called MyCamera&nbsp; &nbsp; &nbsp; &nbsp; string root = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDcim).ToString() + "/MyCamera/";&nbsp; &nbsp; &nbsp; &nbsp;//create the Directory&nbsp; &nbsp; &nbsp; &nbsp; System.IO.Directory.CreateDirectory(root);&nbsp; &nbsp; &nbsp; &nbsp; File myDir = new File(root);&nbsp; &nbsp; &nbsp; &nbsp; myDir.Mkdir();&nbsp; &nbsp; &nbsp; &nbsp; //Image name&nbsp; &nbsp; &nbsp; &nbsp; string fname = "Image-" + "Image1" + ".png";&nbsp; &nbsp; &nbsp; &nbsp; File file = new File(myDir, fname);&nbsp; &nbsp; &nbsp; &nbsp; Log.Error("FilePath", file.AbsolutePath);&nbsp; &nbsp; &nbsp; &nbsp; if (file.Exists()) file.Delete();&nbsp; &nbsp; &nbsp; &nbsp; Log.Error("FilePath", root + fname);&nbsp; &nbsp; &nbsp; &nbsp; //total path&nbsp; &nbsp; &nbsp; &nbsp; string path = root + fname;&nbsp; &nbsp; &nbsp; &nbsp; try&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var fs = new System.IO.FileStream(path, System.IO.FileMode.OpenOrCreate);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (fs != null)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; finalBitmap.Compress(Bitmap.CompressFormat.Png, 90, fs);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fs.Close();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; catch (Exception e)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.PrintStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; MediaScannerConnection.ScanFile(context, new string[] { file.Path }, new string[] { "image/jpeg" }, null);&nbsp; &nbsp; }请不要忘记添加以下权限。<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

繁星淼淼

请注意,您应该在运行时授予外部存储权限,因为它们是关键权限!您可以在此处阅读更多内容。
随时随地看视频慕课网APP
我要回答