我正在尝试将图像从本地存储中的文件路径加载到imageView。
private final String PATH = "file:///storage/emulated/0/Downloads/image.png"
正如论坛其他地方所建议的,我试图使用Glide加载它:
Glide.with(this)
.load(PATH)
.into(imageView);
和Bitmap / BitmapFactory:
ImageView imageView = (ImageView) findViewById(R.id.imageView);
File f = new File(PATH);
if(f.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(f.getAbsolutePath());
imageView.setImageBitmap(myBitmap);
但我总是得到占位符图片。
在清单中,我添加了WRITE.EXTERNAL.STORAGE和READ.EXTERNAL.STORAGE权限。
尝试调试它似乎在f变量中加载了正确的路径。
感谢您的帮助
编辑:我已经尝试了所有建议的解决方案,但我继续搞定空白屏幕......
我还用一个imageView创建了一个全新的应用程序,以便更好地测试:
package com.example.android.pic;
import android.Manifest;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import java.io.File;
public class MainActivity extends AppCompatActivity {
Uri PATH = Uri.fromFile(new File((Environment.getExternalStorageDirectory().getPath() + "/Pictures/agata.png")));
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int permissionCheck = ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
}
ImageView imageView = (ImageView) findViewById(R.id.pic);
Glide.with(this)
.load(PATH)
.into(imageView);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case 1: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
ImageView imageView = (ImageView) findViewById(R.id.pic);
Glide.with(this)
.load(PATH)
.into(imageView);
} else {
finish();
}
}
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
请帮忙! 感谢
答案 0 :(得分:0)
您的文件路径减速错误。 尝试将PATH更改为
private final StringPATH="/storage/emulated/0/Downloads/image.png"
答案 1 :(得分:0)
您应该使用此代码
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
image.setImageBitmap(selectedImage);
在此代码中,您需要可以使用StringPATH的imageUri:
private final StringPATH="/storage/emulated/0/Downloads/image.png"