How to save a bitmap into phone's gallery? [cl

2019-05-04 01:56发布

问题:

I take a photo and show it in an imageview. Then I get the bitmap from the imageview in my activity and when I press a button I want to save this bitmap into phone's gallery. What should I do?

回答1:

call this function in Button onClick

private void saveImage() {

  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);
       finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
       out.flush();
       out.close();

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

check this save bitmap



回答2:

Try this

        Bitmap toDisk = Bitmap.createBitmap(w1,h1,Bitmap.Config.ARGB_8888); 
        setBitmap(toDisk); 
        Bitmap myBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ban_background);
        Bitmap resizeImage1=Bitmap.createScaledBitmap(myBitmap,590,350,false);
          try {
                    toDisk.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File("/mnt/sdcard/image".jpg")));

                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


回答3:

You will have to get the path to phone's External Storage directory first, then the directory where gallery images are stored. On most Android models this is /mnt/sdcard/pictures but I do not suggest hardcoding this path instead use

Environment.getExternalStorageDirectory(); 

After that just create a File path to that directory and use an outputStream to write your bitmap to that directory.