18

Quiero elegir una imagen de la Galería y copiarla en otra carpeta en la tarjeta SD.Cómo copiar el archivo de imagen de la galería a otra carpeta programáticamente en Android

código para retirar la imagen de la Galería

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

me sale content://media/external/images/media/681 este URI onActivityResult.

quiero copiar la imagen,

Formulario path ="content://media/external/images/media/681

Para path = "file:///mnt/sdcard/sharedresources/ este camino de sdcard en Android.

cómo hacerlo?

Respuesta

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

esperanza de que ayudará u

+19

out.write (data); ¿Qué es "datos"? –

+0

datos serán los bytes [] de la imagen que debe convertir de la imagen – Richa

4

una solución puede ser,

1) leer bytes de flujoEntrada del archivo recogido.

me sale "contenido: // media/externa/imágenes/medios/681" onActivityResult este URI. Puede obtener el nombre del archivo consultando este Uri u get. obtener inputStream de eso. léelo en byte [].

aquí tienes/

Uri u = Uri.Parse ("contenido: // media/externa/imágenes/medios/681");

Cursor cursor = contentResolver.query (u, nulo, nulo, nulo, nulo); hay un nombre de columna "_data", que le devuelva el nombre del archivo, de nombre de archivo que puede crear flujo de entrada,

ahora se puede leer este flujo de entrada

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

Así que tienen datos (matriz de bytes) con Byte de imágenes

2) cree un archivo en sdcard y escriba con byte [] tomado en el paso uno.

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

como fileName que ya tiene desde el método de consulta, use el mismo aquí.

31

Gracias a todos ... Código de Trabajo está aquí ..

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

+0

excelente trabajo ... ayudó de muchas maneras – Jigar

+1

¿Qué es shareinfoactivity? –

0

leía this link, aquí están hablando de cuatro formas de copiar archivos en Java, tan relevante para Android también.

Aunque el autor concluye que el uso de 'canal' como se usa en la respuesta de @Prashant es la mejor manera, incluso puede explorar otras formas.

(I han intentado dos primeros, y los dos se encuentran trabajo)

0

Aunque he upvoted la respuesta por @AAnkit, me prestó y siguió adelante para modificar algunos artículos. Menciona usar Cursor pero sin la ilustración adecuada puede ser confuso para los novatos.

Creo que esto es más simple que la respuesta más votada.

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

    } 
} 
Cuestiones relacionadas