Java 从外部存储器读取图像/文件

Java 从外部存储器读取图像/文件,java,android,image,file-io,bitmap,Java,Android,Image,File Io,Bitmap,我正在尝试从外部存储器加载映像。我设置了权限,尝试了不同的方法,但都不起作用 BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.ARGB_8888; Bitmap bitmap = BitmapFactory.decodeFile(file.toString()); tv.setImageBitmap(bitma

我正在尝试从外部存储器加载映像。我设置了权限,尝试了不同的方法,但都不起作用

BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;

    Bitmap bitmap = BitmapFactory.decodeFile(file.toString()); 

    tv.setImageBitmap(bitmap);
而这个,

FileInputStream streamIn = new FileInputStream(file);
Bitmap bitmap = BitmapFactory.decodeStream(streamIn); 

    tv.setImageBitmap(bitmap);
        streamIn.close();

如果SD卡上有文件
abc.jpg
,则:

String photoPath = Environment.getExternalStorageDirectory() + "/abc.jpg";
并获取
位图

BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);

为了避免内存不足错误我建议您使用以下代码

BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
final Bitmap b = BitmapFactory.decodeFile(photoPath, options);

为了避免上述问题,您可以使用毕加索(Android强大的图像下载和缓存库)

怎么做

Picasso.with(context).load("file:///android_asset/DvpvklR.png").into(imageView2);
Picasso.with(context).load(new File(...)).into(imageView3);

从文件夹中获取图像的路径,如下所示。然后将文件解码为位图

   File file= new File(android.os.Environment.getExternalStorageDirectory(),"Your folder");
   Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath())

如果您有文件路径,只需直接使用BitmapFactory,但告诉它使用保留alpha的格式:

BitmapFactory.Options options = new BitmapFactory.Options();

options.inPreferredConfig = Bitmap.Config.ARGB_8888;

Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
selected_photo.setImageBitmap(bitmap);

有一个函数叫做

createFromPath(String)
在绘画课上。 所以声明

String path="/storage/..<just type in the path>";
Drawable.createFromPath(path);
String path=“/storage/”;
Drawable.createFromPath(路径);

将返回一个可绘制对象

上面代码中的tv是什么。这是文本视图吗?我没有收到任何错误,因为我输入了一个try-and-catch,但是如果我没有它,应用程序就会崩溃。ImageView tv=(ImageView)findViewById(R.id.imageView1);调试期间不要使用静默捕捉块。确保您至少打印出任何异常的堆栈跟踪-否则您将只能猜测,并最终发布一个不完整的问题。基于这个理由投票结束这个问题,因为你显然在一年前解决了你的问题。我让它工作了,我想我的方式很好,问题是我试图将它作为一个函数运行,然后调用一个函数,如果我不使用函数,它会工作。我不知道为什么我使用函数时它不起作用。你会在哪里定义函数?你可以在哪里调用它?这对我有帮助:)谢谢如果我使用这个“options.inSampleSize=8”;图像会变得非常小,清晰度也会降低。
createFromPath(String)
String path="/storage/..<just type in the path>";
Drawable.createFromPath(path);