Unable to decode stream: java.io.FileNotFoundException (Permission denied) [duplicate]

北城余情 提交于 2021-01-29 15:43:22

问题


I am trying to upload multiple images from gallery at once. given here. The issue i am facing is converting the string to bitmap. I got the following error.

E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/DCIM/Screenshots/Screenshot_2018-11-05-14-59-33-023_com.android.mms.png (Permission denied)

The error occurs here.

Bitmap bitmap2 = PhotoLoader.init().from(imagePath).requestSize(512, 512).getBitmap();

final String encodedString = ImageBase64.encode(bitmap2); // getting the exception

but in my Log.e there is value in imagepath but cant get value in bitmap2.

ButtonCode to upload images to server is below.

 buttonmultiUpload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

           Toast.makeText(getApplicationContext(), "Upload button is clicked" + imagesEncodedList, Toast.LENGTH_LONG).show();
            Log.e("list","imagesEncodedList" + imagesEncodedList );
            for( String imagePath: imagesEncodedList){
                try {

                    Log.e("imagePath","imagePath" + imagePath );

                   Bitmap bitmap2 = PhotoLoader.init().from(imagePath).requestSize(512, 512).getBitmap();
                   final String encodedString = ImageBase64.encode(bitmap2);
                    Log.e("bitmap","bitmap" + bitmap2 );
                    String url = "http://myserver.com/imageuploadtest/upload.php";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                          Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
                          //  gvGallery.setAdapter(null);
                            new AlertDialog.Builder(MainActivity.this).setTitle("Succesful")
                                    .setMessage("Multiple Prescription of Outdoor has been submitted")
                                    .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                        }
                                    }).show();

                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(getApplicationContext(), "Error while uploading image", Toast.LENGTH_SHORT).show();
                        }
                    }){
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> params = new HashMap<>();

                            params.put("image", encodedString);
                            params.put("empcode", emp_code);
                            return params;
                        }
                    };
                    myCommand.add(stringRequest);

                } catch (FileNotFoundException e) {
                    Toast.makeText(getApplicationContext(), "Error while loading image", Toast.LENGTH_SHORT).show();
                }
            }

            myCommand.execute();

        }
    });

code of Activity result

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


        Toast.makeText(getApplicationContext(), "Clicked for multiple image", Toast.LENGTH_LONG).show();

        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        imagesEncodedList = new ArrayList<String>();
        if(data.getData()!=null){

            Uri mImageUri=data.getData();

            try {
bitmap=BitmapFactory.decodeStream(getContentResolver().openInputStream(mImageUri));
                   bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), mImageUri);

            } catch (IOException e) {
                e.printStackTrace();
            }

            setToImageView(getResizedBitmap(bitmap, 2048));

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

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

            ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
            mArrayUri.add(mImageUri);

            galleryAdapter = new GalleryAdapter(getApplicationContext(),mArrayUri);
            gvGallery.setAdapter(galleryAdapter);
            gvGallery.setVerticalSpacing(gvGallery.getHorizontalSpacing());
            ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) gvGallery.getLayoutParams();
            mlp.setMargins(0, gvGallery.getHorizontalSpacing(), 0, 0);

        } else {
            if (data.getClipData() != null) {
                ClipData mClipData = data.getClipData();
                ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
                for (int i = 0; i < mClipData.getItemCount(); i++) {

                    ClipData.Item item = mClipData.getItemAt(i);
                    Uri uri = item.getUri();
                    mArrayUri.add(uri);

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

                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    imageEncoded  = cursor.getString(columnIndex);
                    imagesEncodedList.add(imageEncoded);
                    cursor.close();

                    galleryAdapter = new GalleryAdapter(getApplicationContext(),mArrayUri);
                    gvGallery.setAdapter(galleryAdapter);
                    gvGallery.setVerticalSpacing(gvGallery.getHorizontalSpacing());
                    ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) gvGallery.getLayoutParams();
                    mlp.setMargins(0, gvGallery.getHorizontalSpacing(), 0, 0);

                }
                Log.v("LOG_TAG", "Selectedmages  " + mArrayUri.size());
                Log.v("LOG_TAG", "Selectedmages  " +  imagesEncodedList );
                Log.v("LOG_TAG", "Selectedmages  " +  bitmap );
            }
        }
    }

回答1:


Add these two to Mainfest.xml file

   <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Then you need to request permission before any operation dynamically like below

if (ContextCompat.checkSelfPermission(thisActivity,Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {
    // Permission is not granted
     if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
            Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
        // Show an explanation to the user *asynchronously* -- don't block
        // this thread waiting for the user's response! After the user
        // sees the explanation, try again to request the permission.
    } else {
        // No explanation needed; request the permission
        ActivityCompat.requestPermissions(thisActivity,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE);
    }
}



回答2:


After android 6.0, only declare permissions request in AndroidManifest.Xml is not enough, you also explicitly request corresponding permissions before doing some task.

ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    1);

and

@Override
public void onRequestPermissionsResult(int requestCode,
    String permissions[], int[] grantResults) {
    switch (requestCode) {
        case 1:
            {
                if (grantResults.length > 0 &&
                    grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // permission was granted, do something you want        
                } else {
                    // permission denied
                    Toast.makeText(MainActivity.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();
                }
                return;
            }
    }
}


来源:https://stackoverflow.com/questions/53358582/unable-to-decode-stream-java-io-filenotfoundexception-permission-denied

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!