18

tôi muốn chọn hình ảnh từ Thư viện và sao chép nó vào Thư mục khác trong SDCard.Cách Sao chép Tệp Hình ảnh từ Bộ sưu tập sang một thư mục khác theo lập trình trong Android

Mã để Chọn ảnh từ Bộ sưu tập

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

tôi nhận được content://media/external/images/media/681 URI onActivityResult này.

Tôi muốn sao chép các hình ảnh,

Mẫu path ="content://media/external/images/media/681

Để path = "file:///mnt/sdcard/sharedresources/ con đường này của sdcard trong Android.

cách thực hiện việc này?

Trả lời

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

Hy vọng nó sẽ giúp u

+19

out.write (dữ liệu); "dữ liệu" là gì ?? –

+0

dữ liệu sẽ là byte [] của hình ảnh mà bạn phải chuyển đổi từ hình ảnh – Richa

4

một giải pháp có thể là,

1) đọc byte từ inputStream của tệp đã chọn.

tôi nhận được "content: // media/external/images/media/681" URI này onActivityResult. Bạn có thể lấy tên tệp bằng cách truy vấn Uri u này. lấy inputStream của nó. đọc nó thành byte [].

đây bạn đi/

Uri u = Uri.Parse ("Nội dung: // media/bên ngoài/images/media/681");

Con trỏ trỏ = contentResolver.query (u, null, null, null, null); có một tên cột "_data" mà sẽ đưa bạn trở tên tập tin, từ tên tập tin bạn có thể tạo inputstream,

bây giờ bạn có thể đọc input stream này

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

Vì vậy, bạn có dữ liệu (mảng byte) với hình ảnh byte

2) tạo tệp trên sdcard và ghi bằng byte [] được thực hiện trong bước một.

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

dưới tên tệp bạn đã có từ phương thức truy vấn, sử dụng cùng ở đây.

31

Nhờ tất cả ... Mã công tác là ở đây ..

 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 cho copyFile(). –

+0

công việc tuyệt vời .. đã giúp theo nhiều cách – Jigar

+1

hoạt động shareinfoactivity là gì? –

0

Đã được đọc this link, ở đây họ đang nói về bốn cách để sao chép tập tin trong Java, cũng phù hợp với Android.

Mặc dù tác giả kết luận rằng việc sử dụng 'kênh' như được sử dụng trong câu trả lời của @ Prashant là cách tốt nhất, bạn thậm chí có thể khám phá các cách khác.

(Tôi đã thử hai đầu tiên, và cả trong số họ làm việc tìm)

0

Mặc dù tôi đã bỏ phiếu tán câu trả lời bằng cách @AAnkit, tôi mượn và đã đi trước để sửa đổi một số mặt hàng. Ông đề cập đến việc sử dụng Cursor nhưng không có minh họa thích hợp, nó có thể gây nhầm lẫn cho người mới.

Tôi nghĩ điều này đơn giản hơn câu trả lời được bỏ phiếu nhiều nhất.

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

    } 
} 
Các vấn đề liên quan