Как копировать файл изображения из галереи в другую папку программно в Android
Я хочу выбрать изображение из галереи и скопировать его в другую папку на SDCard.
Код для выбора изображения из галереи
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 наActivityResult.
Я хочу скопировать изображение,
Form path ="content://media/external/images/media/681
To path = "file:///mnt/sdcard/sharedresources/
это путь sdcard в Android.
Как это сделать?
Ответы
Ответ 1
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();
Надеюсь, что это поможет u
Ответ 2
Спасибо всем... Рабочий код здесь..
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);
}
Ответ 3
одно решение может быть,
1) читать байты из inputStream выбранного файла.
i получить "content://media/external/images/media/681" этот URI onActivityResult. Вы можете получить имя файла, запросив этот Uri u got. получите inputStream. прочитайте его в байт [].
здесь вы идете /
Uri u = Uri.Parse( "content://media/external/images/media/681" );
Курсор курсор = contentResolver.query(u, null, null, null, null);
есть имя столбца "_data", которое вернет вам имя файла, из имени файла вы можете создать входной поток,
теперь вы можете прочитать этот поток ввода
byte data=new byte[fis.available()];
fis.read(data);
Итак, у вас есть данные (байтовый массив) с изображениями
2) создайте файл на sdcard и напишите с байтом [], сделанным на первом шаге.
File file=new File(fileOnSD.getAbsolutePath() +"your foldername", fileName);
FileOutputStream fout=new FileOutputStream(file, false);
fout.write(data);
как имя файла, которое у вас уже есть из метода запроса, используйте его здесь.
Ответ 4
Прочитал эту ссылку, здесь речь идет о четырех способах копирования файлов на Java,
так и для андроида.
Хотя автор приходит к выводу, что использование "канала", используемого в ответе @Prashant, является наилучшим способом, вы можете даже исследовать другие способы.
(я пробовал первые два, и оба они находят работу)
Ответ 5
Несмотря на то, что я получил ответ от @AAnkit, я позаимствовал и пошел, чтобы изменить некоторые элементы. Он упоминает использовать 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();
}
}
}