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

    } 
} 
相关问题