【问题标题】:Picking images from gallery (SD Card) on my app… ¿How to allow only max 500kb photos?在我的应用程序上从图库(SD 卡)中挑选图像... ¿如何只允许最大 500kb 的照片?
【发布时间】:2011-01-31 16:44:11
【问题描述】:

我现在做了什么: 我正在使用 android 在我的应用程序上挑选图像,并将它们显示在我的布局的 ImageView 上,有时我得到一个异常 java.lang.OutOfMemoryError: bitmap size exceeds VM budget。当照片大于 500kb 时会发生这种情况。

我需要做什么(我不知道该怎么做): 然后,我想做的是只允许用户选择最大 500kb 的照片。如果用户选择了一张大于 500kb 的照片,那么,我的应用程序应该显示一个 toast,告诉用户只能选择最大 500kb 的照片.... ¿怎么做?

这是我的代码:

changeImageButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Intent i = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
                startActivityForResult(i, ACTIVITY_SELECT_IMAGE);
            }
        }); 



protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
        super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 

        switch(requestCode) {
        case 1:
        {
            setResult(1);
            finish();    
        }
        case ACTIVITY_SELECT_IMAGE:
            if(resultCode == RESULT_OK){  
                Uri selectedImage = imageReturnedIntent.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String filePath = cursor.getString(columnIndex);
                cursor.close();

                selectedPhoto = BitmapFactory.decodeFile(filePath);
                //profileImage.setImageBitmap(selectedPhoto);
                profileImage.setImageBitmap(Bitmap.createScaledBitmap(selectedPhoto, 80, 80, false));
            }
        }
    }

profileImage 是我的布局的 ImageView。我使用缩放的 butmap 将图像重新调整为 80x80

请给我一些帮助,我在谷歌上搜索,我什么也找不到

【问题讨论】:

    标签: android bitmap imageview android-gallery


    【解决方案1】:

    你不能只使用一些标准的 Java 来获取文件大小,然后检查你的限制吗?

    private long getFileSize(String path) {
        File file = new File(path);
        if (file.exists() && file.isFile()) {
            return file.length();
        } else {
            return 0L;
        }
    }
    

    【讨论】:

      【解决方案2】:

      你为什么这么讨厌你的用户?您问错了问题...您根本不需要限制文件大小。问题在于解压缩后的图像大小,您可以控制它。

      使用带有BitmapFactory.Options 参数的BitmapFactory.decodeFile() 版本,然后将选项参数的inSampleSize 字段设置为适当的值(2 或4 或其他值)。您甚至可能想先使用inJustDecodeBounds 来计算出一个合理的值。

      【讨论】:

      • @AndroidUser99:这是正确的做法。不要将您的用户限制在小图像上。您可以通过这种方式加载非常大的文件而不会出现内存问题。
      • @reuben Scratton @ Savvas Dalkitsis 如果我们减小所有选定图像的大小,那么用户可以选择的最大图像数量是多少?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多