2014-02-01 5 views
1

В моем приложении я хочу выбрать изображение из галереи и отобразить изображение в ImageView, а также перенести изображение в новую папку. Я получил изображение в ImageView, но он не перемещается в другую папку. Может кто-нибудь мне помочь? я сильфон кода для достижения этой цели ....Скопируйте изображение из одной папки в другую в галерее

button.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View arg0) { 
      Intent intent = new Intent(Intent.ACTION_PICK); 
      intent.setType("image/*"); 
      startActivityForResult(intent, 1); 

     } 
    }); 

В onActivityResult

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) { 
     Uri selectedImage = data.getData(); 
     String[] filePathColumn = { MediaStore.Images.Media.DATA }; 

     System.out.println("File Path Column "+filePathColumn); 

     Cursor cursor = getContentResolver().query(selectedImage, 
       filePathColumn, null, null, null); 
     cursor.moveToFirst(); 

     int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
     System.out.println("Column Index "+columnIndex); 
     picturePath = cursor.getString(columnIndex); 
     cursor.close(); 
     //imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath)); 

     BitmapFactory.Options options=new BitmapFactory.Options(); 
     options.inSampleSize = 3; 
     Bitmap preview_bitmap=BitmapFactory.decodeFile(picturePath,options); 
     System.out.println("Image patha in Messaging "+picturePath); 
     imageView.setImageBitmap(preview_bitmap); 
     differentpic.setText("Click on Upload if you wish to solve a different pic"); 
     differentpic.setPadding(0, 0, 0, 30); 

     OutputStream out; 
     File direct = new File(Environment.getExternalStorageDirectory() 
       + "/Solve"); 

     if (!direct.exists()) { 
      direct.mkdirs(); 
     } 
     File file = new File(Environment.getExternalStorageDirectory()+ "/Solve"+String.valueOf(System.currentTimeMillis())+"jpg"); 
     ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
     try { 
     file.createNewFile(); 
     out = new FileOutputStream(file);      
     //Bitmap bmp = intent.getExtras().get("data"); 
     //ByteArrayOutputStream stream = new ByteArrayOutputStream(); 

     int bytes = preview_bitmap.getByteCount(); 
     //or we can calculate bytes this way. Use a different value than 4 if you don't use 32bit images. 
     //int bytes = b.getWidth()*b.getHeight()*4; 

     ByteBuffer buffer = ByteBuffer.allocate(bytes); //Create a new buffer 
     preview_bitmap.copyPixelsToBuffer(buffer); //Move the byte data to the buffer 

     byte[] array = buffer.array(); 


      out.write(array); 
      out.close(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 


     // TODO Auto-generated catch block 


    } 

} 

Что я сделал неправильно?

Заранее спасибо

ответ

8

Если у вас есть путь обоих файлов Исходный_файл и destinationFile, то вы можете скопировать файл, используя следующий код.

/** 
* copies content from source file to destination file 
* 
* @param sourceFile 
* @param destFile 
* @throws IOException 
*/ 
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(); 
    } 

} 
+0

я знаю назначения, но я не знаю, источник ... это может быть любая папка – user3226274

+0

да ... но вы получите путь выбранного файла в onActivityResult() –

+0

Да ... я попробовал, но я получаю ответ – user3226274

0

Проверить код ниже

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

извините, я не могу понять onActivityResult() .. может у меня объяснить – user3226274

Смежные вопросы