Android将位图保存到SD卡

Joh*_*red 19 alert android image bitmap

我有一个按钮,我希望当我点击它时图像被保存到SD卡(或内部存储器,如在htc一个x我们没有像SD卡那样的外部存储器)

这是我的代码:

            sd.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                MpClick.start();
                File myDir=new File("/sdcard/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);
                       bitMapToShare.compress(Bitmap.CompressFormat.JPEG, 600, out);
                       out.flush();
                       out.close();

                } catch (Exception e) {
                       e.printStackTrace();
                }
            }
        });
Run Code Online (Sandbox Code Playgroud)

如何在其中显示一条消息,其中写着"您的图像已保存".像一个警报但是2秒然后消失

Raj*_*ddy 89

试试这个

private void SaveImage(Bitmap finalBitmap) {

   String root = Environment.getExternalStorageDirectory().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);
       out.flush();
       out.close();

   } catch (Exception e) {
       e.printStackTrace();
   }
}
Run Code Online (Sandbox Code Playgroud)

并在清单中添加此项

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
Run Code Online (Sandbox Code Playgroud)

看看这个答案Android保存文件到外部存储

编辑:通过使用此行,您可以在图库视图中查看已保存的图像.

sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
        Uri.parse("file://" + Environment.getExternalStorageDirectory())));
Run Code Online (Sandbox Code Playgroud)

  • 没问题,问题是任何面临我问题的人的画廊缓存,使用此代码,它将工作sendBroadcast(新的Intent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://"+ Environment.getExternalStorageDirectory()) )); (4认同)
  • 使用日期戳而不是随机数可能更好,以避免重复. (3认同)