18

我想從圖庫中選取圖像並將其複製到SDCard中的其他文件夾。如何在Android中以編程方式將圖庫文件從圖庫複製到其他文件夾

代碼從庫

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

我得到這個content://media/external/images/media/681 URI onActivityResult選擇圖片。

我想複製的圖像,

形式path ="content://media/external/images/media/681

path = "file:///mnt/sdcard/sharedresources/ SD卡在Android的這條道路。

該怎麼辦?

回答

11
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(); 

希望這將有助於ü

+19

out.write(data);什麼是「數據」? – 2011-12-29 06:31:55

+0

數據將是圖像的字節[],您必須將圖像 – Richa 2011-12-29 06:44:48

4

一個解決方案可以是,

1)從拾取文件的inputStream中讀取字節。

我得到 「內容://媒體/外部/圖像/媒體/ 681」 這個URI onActivityResult。 你可以通過查詢這個Uri得到的文件名。得到它的inputStream。讀入byte []。

在這裏你走/

烏里U = Uri.Parse( 「內容://媒體/外部/圖像/媒體/ 681」);

遊標遊標= contentResolver.query(u,null,null,null,null); 有一列名爲「_data」,這將返回的文件名,從文件名可以創建的InputStream,

你現在可以讀取此輸入流

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

所以,你必須用數據(字節數組)圖像字節

2)創建一個文件到SD卡上,並寫入字節[]在第一步中採取。

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

作爲fileName您已經從查詢方法中獲得,請在此使用相同的名稱。

31

感謝所有...工作代碼是在這裏..

 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); 
    } 
+0

+1轉換爲copyFile()。 – 2013-12-07 10:35:38

+0

偉大的工作..在很多方面幫助 – Jigar 2014-12-29 13:28:13

+1

什麼是shareinfoactivity? – 2015-07-27 09:39:22

0

在讀this link,在這裏,他們都在談論四種方式複製文件Java, 也與android相關。

雖然作者的結論是,使用@Prashant的答案中使用的'頻道'是最好的方法,你甚至可以探索其他方式。

(我已經試過前兩種,兩者的工作找到)

0

即使我已經@AAnkit upvoted答案,我借,徑自修改一些項目。他提到使用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(); 
     } 

    } 
} 
相關問題