无法解码流:java.io.FileNotFoundException(权限被拒绝)

时间:2018-11-18 06:52:20

标签: android android-bitmap

我正在尝试一次从图库中上传多个图像。在这里给出。我面临的问题是将字符串转换为位图。我收到以下错误。

  

E / BitmapFactory:无法解码流:java.io.FileNotFoundException:/storage/emulated/0/DCIM/Screenshots/Screenshot_2018-11-05-14-59-33-023_com.android.mms.png(权限拒绝)

此处发生错误。

  

位图bitmap2 = PhotoLoader.init()。from(imagePath).requestSize(512,512).getBitmap();

     

最终字符串encodingString = ImageBase64.encode(bitmap2); //获取异常

但是在我的Log.e中,imagepath中有值,但bitmap2中却没有值。

将图片上传到服务器的按钮代码如下。

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

        }
    });

活动结果代码

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

2 个答案:

答案 0 :(得分:0)

将这两个添加到Mainfest.xml文件中

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

然后您需要先请求权限,然后才能像下面这样动态地进行任何操作

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

答案 1 :(得分:-1)

在android 6.0 之后,仅在AndroidManifest.Xml中声明权限请求是不够的,您还需要在执行某些任务之前显式请求相应的权限。

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

@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;
            }
    }
}