如何将位图保存到android库

不幸的是,我发现的解决方案不适用于Android 5.1.1。 我有一个名为source的位图。 我需要将它直接保存到我手机的图库中。 我的清单包含你能给我一个工作方法吗?

使用这一个:

 private void saveImage(Bitmap finalBitmap, String image_name) { String root = Environment.getExternalStorageDirectory().toString(); File myDir = new File(root); myDir.mkdirs(); String fname = "Image-" + image_name+ ".jpg"; File file = new File(myDir, fname); if (file.exists()) file.delete(); Log.i("LOAD", root + fname); try { FileOutputStream out = new FileOutputStream(file); finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } } 

在One Line MediaStore.Images.Media.insertImage(applicationContext.getContentResolver(), IMAGE ,"nameofimage" , "description");

使用此代码,我们可以帮助您将图像存储到特定文件夹中,该文件夹是saved_images,文件夹图像立即显示在图库中。

 private void SaveImage(Bitmap finalBitmap) { String root = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES).toString(); File myDir = new File(root + "/saved_images"); myDir.mkdirs(); Random generator = new Random(); int n = 10000; n = generator.nextInt(n); String fname = "Image-"+ n +".jpg"; File file = new File (myDir, fname); if (file.exists ()) file.delete (); try { FileOutputStream out = new FileOutputStream(file); finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); // sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, // Uri.parse("file://"+ Environment.getExternalStorageDirectory()))); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } // Tell the media scanner about the new file so that it is // immediately available to the user. MediaScannerConnection.scanFile(this, new String[]{file.toString()}, null, new MediaScannerConnection.OnScanCompletedListener() { public void onScanCompleted(String path, Uri uri) { Log.i("ExternalStorage", "Scanned " + path + ":"); Log.i("ExternalStorage", "-> uri=" + uri); } }); }