【问题标题】:How to Copy Image File from Gallery to another folder programmatically in Android如何在 Android 中以编程方式将图像文件从图库复制到另一个文件夹
【发布时间】:2012-01-29 16:04:12
【问题描述】:

我想从图库中挑选图像并将其复制到 SDCard 的其他文件夹中。

从图库中选择图片的代码

Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
    photoPickerIntent.setType("image/*");
    startActivityForResult(photoPickerIntent, REQUEST_CODE_CHOOSE_PICTURE_FROM_GALLARY);

我在ActivityResult 上得到content://media/external/images/media/681 这个URI。

我想复制图片,

表格path ="content://media/external/images/media/681

path = "file:///mnt/sdcard/sharedresources/这个Android中的sdcard路径。

如何做到这一点?

【问题讨论】:

    标签: android android-intent android-gallery android-contentprovider android-file


    【解决方案1】:

    感谢大家...工作代码在这里..

         private OnClickListener photoAlbumListener = new OnClickListener(){
              @Override
              public void onClick(View arg0) {
                Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
                imagepath = Environment.getExternalStorageDirectory()+"/sharedresources/"+HelperFunctions.getDateTimeForFileName()+".png";
                uriImagePath = Uri.fromFile(new File(imagepath));
                photoPickerIntent.setType("image/*");
                photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT,uriImagePath);
                photoPickerIntent.putExtra("outputFormat",Bitmap.CompressFormat.PNG.name());
                photoPickerIntent.putExtra("return-data", true);
                startActivityForResult(photoPickerIntent, REQUEST_CODE_CHOOSE_PICTURE_FROM_GALLARY);
    
              }
          };
    
       protected void onActivityResult(int requestCode, int resultCode, Intent data) {
               if (resultCode == RESULT_OK) {
                    switch(requestCode){
                   
                  
                     case 22:
                            Log.d("onActivityResult","uriImagePath Gallary :"+data.getData().toString());
                            Intent intentGallary = new Intent(mContext, ShareInfoActivity.class);
                            intentGallary.putExtra(IMAGE_DATA, uriImagePath);
                            intentGallary.putExtra(TYPE, "photo");
                            File f = new File(imagepath);
                            if (!f.exists())
                            {
                                try {
                                    f.createNewFile();
                                    copyFile(new File(getRealPathFromURI(data.getData())), f);
                                } catch (IOException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            }
                            
                            startActivity(intentGallary);
                            finish();
                     break;
                     
                     
                    }
                  }
               
               
            
              
            
       }
    
       private void copyFile(File sourceFile, File destFile) throws IOException {
                if (!sourceFile.exists()) {
                    return;
                }
                
                FileChannel source = null;
                    FileChannel destination = null;
                    source = new FileInputStream(sourceFile).getChannel();
                    destination = new FileOutputStream(destFile).getChannel();
                    if (destination != null && source != null) {
                        destination.transferFrom(source, 0, source.size());
                    }
                    if (source != null) {
                        source.close();
                    }
                    if (destination != null) {
                        destination.close();
                    }
                
                
        }
    
        private String getRealPathFromURI(Uri contentUri) {
        
           String[] proj = { MediaStore.Video.Media.DATA };
           Cursor cursor = managedQuery(contentUri, proj, null, null, null);
           int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
           cursor.moveToFirst();
           return cursor.getString(column_index);
        }
    

    【讨论】:

    • 什么是 shareinfoactivity ?
    • 您好,请问上面代码中HelperFunctions.getDateTimeForFileName()的意义是什么?
    【解决方案2】:
    OutputStream out;
                String root = Environment.getExternalStorageDirectory().getAbsolutePath()+"/";
                File createDir = new File(root+"Folder Name"+File.separator);
                if(!createDir.exists()) {
                    createDir.mkdir();
                }
                File file = new File(root + "Folder Name" + File.separator +"Name of File");
                file.createNewFile();
                out = new FileOutputStream(file);                       
    
            out.write(data);
            out.close();
    

    希望对你有帮助

    【讨论】:

    • out.write(data);什么是“数据”??
    • 数据将是您必须从图像转换的图像的字节[]
    • 这是推荐的方式还是最好的方式?
    【解决方案3】:

    一个解决方案可以,

    1) 从所选文件的 inputStream 中读取字节。

    我得到“content://media/external/images/media/681”这个URI onActivityResult。 你可以通过查询你得到的这个 Uri 来获取文件名。获取它的 inputStream。将其读入字节[]。

    给你/

    Uri u = Uri.Parse("content://media/external/images/media/681");

    Cursor cursor = contentResolver.query(u, null, null, null, null); 有一个列名“_data”,它将返回文件名,您可以从文件名创建输入流,

    您现在可以读取此输入流

             byte data=new byte[fis.available()];
              fis.read(data);
    

    所以你有图像字节的数据(字节数组)

    2) 在 sdcard 上创建一个文件,并使用第一步中获取的 byte[] 进行写入。

           File file=new File(fileOnSD.getAbsolutePath() +"your foldername", fileName);
            FileOutputStream fout=new FileOutputStream(file, false);
            fout.write(data);
    

    作为你已经从查询方法中获得的文件名,在这里使用相同的。

    【讨论】:

    • URi.Parse 非常有用。因此,您可以将 URi 保存为字符串,然后在需要时将其解析为 URi。
    【解决方案4】:

    正在阅读this link,这里他们在谈论用Java复制文件的四种方法, 与android也很相关。

    虽然作者得出结论,使用@Prashant 的答案中使用的“频道”是最好的方法,但您甚至可以探索其他方法。

    (我已经尝试了前两个,它们都可以找到)

    【讨论】:

      【解决方案5】:

      尽管我对@AAnkit 的答案表示赞同,但我还是借用并继续修改了一些项目。他提到使用Cursor,但如果没有适当的说明,新手可能会感到困惑。

      我认为这比投票最多的答案更简单。

      String mCurrentPhotoPath = "";
      
      
      private File createImageFile() throws IOException {
          String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
          String imageFileName = "JPEG_" + timeStamp + "_";
          File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
          File image = File.createTempFile(
                  imageFileName,  /* prefix */
                  ".jpg",         /* suffix */
                  storageDir      /* directory */
          );
      
          mCurrentPhotoPath = image.getAbsolutePath();
          return image;
      }
      
      
                         /*Then I proceed to select from gallery and when its done selecting it calls back the onActivityResult where I do some magic*/
      
      
      private void snapOrSelectPicture() {
          Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
          if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
              File photoFile = null;
              try {
                  photoFile = createImageFile();
              } catch (IOException ex) {
                  ex.printStackTrace();
              }
              if (photoFile != null) {
                  Uri photoURI = FileProvider.getUriForFile(this,
                          "com.example.android.fileprovider",
                          photoFile);
                  takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                  startActivityForResult(Intent.createChooser(takePictureIntent, "SELECT FILE"), 1001);
              }
          }
      }
      
      @Override
      protected void onActivityResult(int requestCode, int resultCode, Intent data) {
          if (resultCode == RESULT_OK) {
      
              try {
                  /*data.getDataString() contains your path="content://media/external/images/media/681 */
      
                  Uri u = Uri.parse(data.getDataString());
                  Cursor cursor = getContentResolver().query(u, null, null, null, null);
                  cursor.moveToFirst();
                  File doc = new File(cursor.getString(cursor.getColumnIndex("_data")));
                  File dnote = new File(mCurrentPhotoPath);
                  FileOutputStream fout = new FileOutputStream(dnote, false);
                  fout.write(Files.toByteArray(doc));
              } catch (Exception e) {
                  e.printStackTrace();
              }
      
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2017-01-04
        • 1970-01-01
        • 1970-01-01
        • 2018-03-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-29
        • 2020-07-30
        相关资源
        最近更新 更多