[英]Move a picture from gallery to drawable using code. [android studio]
I am using this two functions to open the image gallery and to choose a picture. 我正在使用这两个功能来打开图片库并选择图片。 I have the uri of the picture and the picture itself in "inputStream". 我在“ inputStream”中具有图片的uri和图片本身。 My question is how can I move the picture or to copy it in the folder drawable from android studio ? 我的问题是如何移动图片或将其复制到可从android studio绘制的文件夹中?
public void onImageGalleryClicked(View v) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureDirectoryPath = pictureDirectory.getPath();
Uri data = Uri.parse(pictureDirectoryPath);
photoPickerIntent.setDataAndType(data, "image/*");
startActivityForResult(photoPickerIntent, IMAGE_GALLERY_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == IMAGE_GALLERY_REQUEST)
Uri imageUri = data.getData();
InputStream inputStream;
try {
inputStream = getContentResolver().openInputStream(imageUri);
} catch (FileNotFoundException e) {
e.printStackTrace()
Toast.makeText(this, "Unable to open image", Toast.LENGTH_LONG).show();
}
}
}
}
I would have done it like below: 我会像下面这样:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode,resultCode,data);
if (resultCode == RESULT_OK) {
if (requestCode == IMAGE_GALLERY_REQUEST) {
Uri imageUri = data.getData();
Long tsLong = System.currentTimeMillis();
String now = tsLong.toString();
String destitaion =folderPath+"/"+now+".jpg";
savefile(imageUri.getPath(),destitaion);
}
}
}
void savefile(String sourceFilename,String destinationFilename)
{
//String sourceFilename= sourceuri.getPath();
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
boolean exp_occuered=false;
try {
bis = new BufferedInputStream(new FileInputStream(sourceFilename));
bos = new BufferedOutputStream(new FileOutputStream(destinationFilename, false));
byte[] buf = new byte[1024];
bis.read(buf);
do {
bos.write(buf);
} while(bis.read(buf) != -1);
} catch (IOException e) {
e.printStackTrace();
exp_occuered=true;
}
finally {
try {
if (bis != null) bis.close();
if (bos != null) bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(!exp_occuered)
{
//the image has been saved properly
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.