我想将手机库中的图片上传到我的应用程序中。在我的应用程序中有一个名为upload的按钮。当我点击按钮时,它应该移动到图库和画廊,如果我选择图像,所选图像应该在应用程序中显示为缩略图。我想从我的应用程序中的库中上传10个图像。
答案 0 :(得分:19)
单击图库按钮,启动startActivityForResult,如下所示:
startActivityForResult(new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI), GET_FROM_GALLERY);
因此,在onActivityResult中检测GET_FROM_GALLERY(这是一个静态int,您选择的任何请求编号,例如public static final int GET_FROM_GALLERY = 3;
)。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Detects request codes
if(requestCode==GET_FROM_GALLERY && resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
答案 1 :(得分:7)
查看图库:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),REQUEST_CODE);
并在您的应用中使用它:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
switch (requestCode) {
case REQUEST_CODE:
if (resultCode == Activity.RESULT_OK) {
//data gives you the image uri. Try to convert that to bitmap
break;
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.e(TAG, "Selecting picture cancelled");
}
break;
}
} catch (Exception e) {
Log.e(TAG, "Exception in onActivityResult : " + e.getMessage());
}
}
答案 2 :(得分:4)
这是要走的路:
startActivityForResult(
new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI
),
GET_FROM_GALLERY
);