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

12

我正在尝试从外部存储加载图像。我已设置权限,尝试了不同的方法,但它们都没有起作用。

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

上面的代码中,tv是什么?是一个TextView吗? - Raghunandan
我没有收到任何错误,因为我加入了try和catch,但如果我没有它,应用程序会崩溃。ImageView tv =(ImageView)findViewById(R.id.imageView1); - Ramin Anushir
1
在调试期间不要使用静默的catch块。确保至少打印任何异常的堆栈跟踪 - 否则你只能猜测,并最终发布一个不完整的问题。基于这个原因,投票关闭该问题,因为你显然已经在一年前解决了你的问题。 - Chris Stratton
5个回答

25
如果我在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);

或者

Bitmap bitmap1 = BitmapFactory.decodeFile(photoPath);

为避免内存错误,我建议您使用以下代码...

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

为了避免上述问题,您可以使用Picasso(一款针对Android的强大图像下载和缓存库)。 文档 如何操作?
Picasso.with(context).load("file:///android_asset/DvpvklR.png").into(imageView2);
Picasso.with(context).load(new File(...)).into(imageView3);

我弄好了,我猜我的写法没问题,问题是我试图将它作为函数运行,然后调用一个函数,如果我不使用函数,它就能工作。我不确定为什么使用函数时它不能工作。你应该在哪里定义函数并在哪里调用它? - Ramin Anushir
这帮助了我..:) 谢谢 - ADT
如果我使用这个 "options.inSampleSize = 8;",图片会变得非常小,清晰度也会降低。 - Prashanth Debbadwar

5
File sdCard = Environment.getExternalStorageDirectory();

File directory = new File (sdCard.getAbsolutePath() + "/Pictures");

File file = new File(directory, "image_name.jpg"); //or any other format supported

FileInputStream streamIn = new FileInputStream(file);

Bitmap bitmap = BitmapFactory.decodeStream(streamIn); //This gets the image

streamIn.close();

0

有一个名为

的函数。
createFromPath(String)

在Drawable类中。 因此该语句

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

将返回一个可绘制对象


0

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

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

0
如果您有文件路径,只需直接使用BitmapFactory,但要告诉它使用保留alpha通道的格式:
BitmapFactory.Options options = new BitmapFactory.Options();

options.inPreferredConfig = Bitmap.Config.ARGB_8888;

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

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