【问题标题】:Android intent - pick image from galleryAndroid 意图 - 从图库中选择图像
【发布时间】:2014-06-19 12:46:33
【问题描述】:

我正在关注此sample code 以发送获取图像的意图。

Intent i = new Intent();
i.setAction(Intent.ACTION_GET_CONTENT);

i.setType("image/*");

if (i.resolveActivity(getPackageManager()) != null) {
     startActivityForResult(i, 3);
}

onActivityResult

if(requestCode == 3 && resultCode == RESULT_OK) {
     Bitmap thumbnail = data.getParcelableExtra("data");

     if(thumbnail == null) {
        Toast.makeText(getApplicationContext(), "Thumbnail is null", Toast.LENGTH_SHORT).show();
        return;
     }

     ImageView iv = (ImageView) findViewById(R.id.imageView);
     iv.setImageBitmap(thumbnail);
 }

发送意图后,图像选择器启动,我选择图库中的一张图像。但是在onActivityResult中,对应示例代码中的如下语句(我在Android 4.4中改为getParcelableExtra):

Bitmap thumbnail = data.getParcelable("data");

我得到的缩略图为空。我正在 Genymotion VM 上进行测试。

我做错了什么?

【问题讨论】:

    标签: android android-intent


    【解决方案1】:
            btnFromGallery.setOnClickListener(new OnClickListener() {
    
                        @Override
                        public void onClick(View v) {
                            // TODO Auto-generated method stub
    
                            try {
                                Intent intent = new Intent();
                                intent.setType("image/*");
                                intent.setAction(Intent.ACTION_GET_CONTENT);
                                Log.i("after select", "get image");
                                startActivityForResult(Intent.createChooser(intent, ""), PICK_IMAGE);
                            } catch (Exception e) {
                                Toast.makeText(getApplicationContext(), R.string.imageException, Toast.LENGTH_LONG).show();
                                Log.e(e.getClass().getName(), e.getMessage(), e);
                            }
                        }
                    });
    
        //onActivityResult code:
    
        @Override
            protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                switch (requestCode) {
    
                case PICK_IMAGE:
                    if (resultCode == Activity.RESULT_OK) {
                        Log.i("On onActivityResult", "on Activity Result");
                        Uri selectedImageUri = data.getData();
                        String filePath = null;
    
                        try {
                            String filemanagerstring = selectedImageUri.getPath();
    
                            selectedImagePath = getPath(selectedImageUri);
                            if (selectedImagePath != null) {
                                filePath = selectedImagePath;
                            } else if (filemanagerstring != null) {
                                filePath = filemanagerstring;
                            } else {
                                Toast.makeText(getApplicationContext(), R.string.unknownPath, Toast.LENGTH_LONG).show();
                            }
    
                            if (filePath != null) {
                                decodeFile(filePath);
                            } else {
                                bitmap = null;
                            }
                        } catch (Exception e) {
                            Toast.makeText(getApplicationContext(), R.string.dataException, Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
    
                }
            }
    
    
    //Get Path Method
    
        public String getPath(Uri uri) {
                String[] projection = { MediaColumns.DATA };
                Cursor cursor = managedQuery(uri, projection, null, null, null);
                if (cursor != null) {
                    int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
                    cursor.moveToFirst();
                    return cursor.getString(column_index);
                } else
                    return null;
            }
    
    //Decode File method
    
    public void decodeFile(String filePath) {
            try {
    
                File f = new File(filePath);
                ExifInterface exif = new ExifInterface(f.getPath());
                int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
    
                int angle = 0;
    
                if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
                    angle = 90;
                } else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
                    angle = 180;
                } else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
                    angle = 270;
                }
    
                Matrix mat = new Matrix();
                mat.postRotate(angle);
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 2;
    
                Bitmap bmp = BitmapFactory.decodeStream(new FileInputStream(f), null, options);
                bitmap = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), mat, true);
                ByteArrayOutputStream outstudentstreamOutputStream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, outstudentstreamOutputStream);
                imgEdit.setImageBitmap(bitmap);
    

    【讨论】:

      【解决方案2】:

      你能试试他的答案吗? How to pick an image from gallery (SD Card) for my app?

      使用getData() 而不是getParcelableExtra()

      它将返回一个 Uri,您需要使用 ContentResolver 来获取图像。

      另外,使用Intent.ACTION_PICK 代替Intent.ACTION_GET_CONTENT

      【讨论】:

        【解决方案3】:

        不是获取位图,而是从数据中获取 URI 并自己加载位图。

                   Uri selectedImageUri = data.getData();
                   String selectedImagePath = getPath(selectedImageUri);
        

        【讨论】:

          【解决方案4】:

          试试这个.. 对你有帮助

            /**
                               * Images uploaded through gallery
                               * 
                               */
          
                              btn_gallery.setOnClickListener(new OnClickListener()
                              {
          
                                  @Override
                                  public void onClick(View v)
                                  {
                                      if (v.getId() == R.id.btn_gallery)
                                      {
                                          upload = true;
                                          gallery_upload();
          
          
                                      }
          
                                  }
                              });
          
          
          
               /**
                       * By this method we can upload the image from gallery
                       */
                      public void gallery_upload()
                      {
                          Log.d("Upload", "inside gallery upload");
                          Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
          
                          startActivityForResult(i, RESULT_LOAD_IMAGE);
          
                      }
          
              @Override
                  protected void onActivityResult(int requestCode, int resultCode, Intent data)
                  {
                      super.onActivityResult(requestCode, resultCode, data);
          
                      if (upload)
                      {
                          if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data)
                          {
                              Uri selectedImage = data.getData();
                              String[] filePathColumn = { MediaStore.Images.Media.DATA };
          
                              Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                              cursor.moveToFirst();
          
                              int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                              picturePath = cursor.getString(columnIndex);
                              Log.e("", "" + picturePath);
                              cursor.close();
          
                              imageView = (ImageView) findViewById(R.id.upload_register_image);
          
                              File image = new File(picturePath);
                              if (image.exists())
                              {
                                  File f = image.getAbsoluteFile();
                                  decodeFile(f);
                              }
                              else
                              {
                                  Log.d("VEHICLEREGISTERATION", "image doesnt exist");
                              }
          
                              upload = false;
          
                              imagePath(picturePath);
          
                          }
              }
              }
          /**
           * Helps to decode size of the image
           * */
          private Bitmap decodeFile(File f)
          {
              try
              {
                  // Decode image size
                  BitmapFactory.Options o = new BitmapFactory.Options();
                  o.inJustDecodeBounds = true;
                  BitmapFactory.decodeStream(new FileInputStream(f), null, o);
          
                  // The new size we want to scale to
                  final int REQUIRED_SIZE = 70;
          
                  // Find the correct scale value. It should be the power of 2.
                  int scale = 1;
                  while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
                      scale *= 2;
          
                  // Decode with inSampleSize
                  BitmapFactory.Options o2 = new BitmapFactory.Options();
                  o2.inSampleSize = scale;
                  Bitmap bit_map = BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
                  imageView.setImageBitmap(bit_map);
          
              }
              catch (FileNotFoundException e)
              {
              }
              return null;
          }
          
          public void imagePath(String Path)
          {
              finalImgPath = Path;
          
          }
          

          【讨论】:

            猜你喜欢
            • 2011-07-15
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-02-15
            相关资源
            最近更新 更多