11

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

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

5 回答 5

25

如果我有文件abc.jpg然后sdcard

String photoPath = Environment.getExternalStorageDirectory() + "/abc.jpg";

并得到bitmap.

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);
于 2013-04-10T06:18:35.317 回答
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();
于 2013-04-10T06:19:06.793 回答
0

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

   File file= new File(android.os.Environment.getExternalStorageDirectory(),"Your folder");
   Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath())
于 2013-04-10T06:28:44.663 回答
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);
于 2014-02-17T12:34:50.037 回答
0

有一个函数叫

createFromPath(String)

在可绘制类中。所以声明

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

将返回一个可绘制对象

于 2016-06-24T06:54:37.307 回答