Search code examples
androidbitmapimageviewandroid-gallery

Picking images from gallery (SD Card) on my app… ¿How to allow only max 500kb photos?


WHAT I HAVE DONE NOW: i am picking images on my app with android, and showing them on a ImageView of my layout, and sometimes i got an exception java.lang.OutOfMemoryError: bitmap size exceeds VM budget. This happens when the photos are higher than 500kb.

WHAT I NEED TO DO (AND I DONT KNOW HOW TO DO IT): then, what i want to do is to allow the user only to select photos of maximum 500kb. And if the user selects a photo Higher than 500kb, then, my app should show a toast telling the user that only can select photos of max 500kb.... ¿how to do it?

this is my code:

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 is a ImageView of my layout. and i use scaled butmap to resice the image to 80x80

please give me some help to do that, im searching on google and i can't find nothing


Solution

  • Can't you just use some standard Java to get the file size, then check against your limit?

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