Android - Save images in an specific folder

后端 未结 5 1493
执笔经年
执笔经年 2020-11-29 22:01

I need to save the pictures taken with my app in an specific folder. I\'ve read many solutions to this problem but I couldn\'t make any of them work so I ask for help.

5条回答
  •  执念已碎
    2020-11-29 22:31

    Use Like this. It will work for you.

    public void onClick(View v) {
      Intent camera = new Intent(
      android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
      startActivityForResult(camera, 1);
    }
    
    protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
      super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
    
      switch(requestCode) {
        case 1:
          if(resultCode == RESULT_OK) {
          Uri selectedImage = imageReturnedIntent.getData();
          String[] filePathColumn = {MediaStore.Images.Media.DATA};
    
          Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
          cursor.moveToFirst();
    
          int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
          //file path of captured image
          filePath = cursor.getString(columnIndex);
          //file path of captured image
          File f = new File(filePath);
          filename= f.getName();
    
          Toast.makeText(getApplicationContext(), "Your Path:"+filePath, 2000).show();
          Toast.makeText(getApplicationContext(), "Your Filename:"+filename, 2000).show();
          cursor.close();
    
          //Convert file path into bitmap image using below line.
          // yourSelectedImage = BitmapFactory.decodeFile(filePath);
          Toast.makeText(getApplicationContext(), "Your image"+yourSelectedImage, 2000).show();
    
          //put bitmapimage in your imageview
          //yourimgView.setImageBitmap(yourSelectedImage);  
    
          Savefile(filename,filePath);
        }
      }
    }
    
    public void Savefile(String name, String path) {
      File direct = new File(Environment.getExternalStorageDirectory() + "/MyAppFolder/MyApp/");
      File file = new File(Environment.getExternalStorageDirectory() + "/MyAppFolder/MyApp/"+n+".png");
    
      if(!direct.exists()) {
        direct.mkdir();
      }
    
      if (!file.exists()) {
        try {
          file.createNewFile();
          FileChannel src = new FileInputStream(path).getChannel();
          FileChannel dst = new FileOutputStream(file).getChannel();
          dst.transferFrom(src, 0, src.size());
          src.close();
          dst.close();
    
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }
    

    Hope this will help you. for reference to use camera intent.

提交回复
热议问题