簡體   English   中英

如何在android中上傳圖庫

[英]How to upload image from gallery in android

我想將手機庫中的圖像上傳到我的應用程序中。在我的應用程序中有一個名為upload的按鈕。 當我點擊按鈕,它應該移動到畫廊和畫廊,如果我選擇圖像,所選圖像應該在應用程序中顯示為縮略圖。我想從我的應用程序中的庫中上傳10個圖像。

單擊圖庫按鈕,啟動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();
        }
    }
}

要查看圖庫:

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

這是要走的路:

startActivityForResult(
  new Intent(
    Intent.ACTION_PICK,
    android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI
  ),
  GET_FROM_GALLERY
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM