如何在 ImageView 中显示从内部存储选择的图像?

8

我是一个新手,正在学习如何在安卓中处理图片。我想从内部存储中加载图像,但是它给了我权限被拒绝的错误提示,然后我已经在android manifest文件中添加了权限。但是,我仍然无法完成我的任务。

以下是我的代码:

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageView image = (ImageView)findViewById(R.id.imageView);
        Bitmap bm = BitmapFactory.decodeFile("/storage/emulated/0/DCIM/Camera/IMG_20151102_193132.jpg");
        image.setImageBitmap(bm);

    }
}

日志记录:

01-16 15:16:11.345 6533-6533/com.example.jaytanna.imagemap E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/DCIM/Camera/IMG_20151102_193132.jpg: open failed: EACCES (Permission denied)

它没有显示任何图像。 请帮我解决这个问题。谢谢。

你能发布一下logcat吗? - Vishnu M Menon
4个回答

16

请检查

     File imgFile = new  File("/storage/emulated/0/DCIM/Camera/IMG_20151102_193132.jpg");
      if(imgFile.exists()){

        Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());

        ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);

        myImage.setImageBitmap(myBitmap);

      };

并在清单文件中包含此权限:

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

对于API 23+,即使权限已经在清单中,您也需要请求读/写权限。

// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
};

/**
 * Checks if the app has permission to write to device storage
 *
 * If the app does not has permission then the user will be prompted to grant permissions
 *
 * @param activity
 */
public static void verifyStoragePermissions(Activity activity) {
    // Check if we have write permission
    int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permission != PackageManager.PERMISSION_GRANTED) {
        // We don't have permission so prompt the user
        ActivityCompat.requestPermissions(
                activity,
                PERMISSIONS_STORAGE,
                REQUEST_EXTERNAL_STORAGE
        );
    }
}

为了处理响应,您可以使用我从http://web.archive.org/web/20160111030837/http://developer.android.com/training/permissions/requesting.html复制的代码 —

@Override
public void onRequestPermissionsResult(int requestCode,
        String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}

关于请求API 23+权限的官方文档,请查看https://developer.android.com/training/permissions/requesting.html


我的文件在内部存储中。 - Jay
将文件路径更改为您的内部存储并运行代码,如果有任何错误,请告诉我,并显示Android Studio错误日志。 - anon
01-16 15:46:51.260 20918-20918/com.example.jaytanna.imagemap E/BitmapFactory: 无法解码流: java.io.FileNotFoundException: /storage/emulated/0/DCIM/Camera/IMG_20151102_193132.jpg: 打开失败: EACCES (权限被拒绝) - Jay
它能工作,但不知何故图像自己旋转了90度。有什么线索是错的吗? - Hiraeths

2

您需要像这样添加运行时权限检查:

    public  boolean isStoragePermissionGranted() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v(TAG,"Permission is granted");
            return true;
        } else {

            Log.v(TAG,"Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
            return false;
        }
    }
    else { //permission is automatically granted on sdk<23 upon installation
        Log.v(TAG,"Permission is granted");
        return true;
    }
}

使用方法:

if(isStoragePermissionGranted()){
 Bitmap bm = BitmapFactory.decodeFile("/storage/emulated/0/DCIM/Camera/IMG_20151102_193132.jpg");
 image.setImageBitmap(bm);

 }

抓取结果在:
    @Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
        Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
        //resume tasks needing this permission
        Bitmap bm = BitmapFactory.decodeFile("/storage/emulated/0/DCIM/Camera/IMG_20151102_193132.jpg");
       image.setImageBitmap(bm);
    }
}

1
将您的onCreate活动之外的第一个和最后一个代码片段复制。 - rafsanahmad007
1
在您的 onCreate() 中添加以下代码片段以替换此代码:Bitmap bm = BitmapFactory.decodeFile("/storage/emulated/0/DCIM/Camera/IMG_20151102_193132.jpg"); image.setImageBitmap(bm); - rafsanahmad007
感谢@rafsanahmad007提供这个有用的答案。它解决了我的问题,链接在这里:https://stackoverflow.com/questions/48317946/how-to-upload-from-android-using-jsch-sftp - Omid1989

1
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
        startActivityForResult(gallery,PICK_IMAGE);

@Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK && requestCode == PICK_IMAGE){
         imageUri = data.getData();
         imageView.setImageURI(imageUri);
        }
    }

这将有效。简单易行。


0
你在应用程序设置中启用了权限吗?(READ_EXTERNAL_STORAGEWRITE_EXTERNAL_STORAGE都会显示为“storage”)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接