从SD卡的图像显示

时间:2014-01-02 19:57:05

标签: android android-image android-sdcard

我是Android新手。在我的应用程序中,我想从我的SD卡访问特定图像。但图像不显示。我在清单中包含了WRITE_EXTERNAL_STORAGE请求。

public class Display extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.display);

    final ImageView imageView = (ImageView) findViewById(R.id.imageView1);
    final TextView name=(TextView) findViewById(R.id.name);
    final TextView phone_no=(TextView) findViewById(R.id.phone_no);

    File f= new File("/storage/sdcard0/Download/images.jpeg");
            Bitmap bMap = BitmapFactory.decodeFile(f.getAbsolutePath());
            imageView.setImageBitmap(bMap);
}

我也尝试过以下代码,但没有用

File mFichier = new File(Environment.getExternalStorageDirectory(),"/storage/sdcard0/Download/images.jpeg");

    if(mFichier.exists())
    {
        imageView.setImageURI(Uri.fromFile(mFichier));
    }

以及此代码

Bitmap mBitmap = BitmapFactory.decodeFile("/storage/sdcard0/Download/images.jpeg"); 
imageView.setImageBitmap(mBitmap);

请帮我解释为什么我的图片没有显示..

1 个答案:

答案 0 :(得分:0)

首先,你想从外部存储器加载文件,比如sdcard,你最好使用下面的代码:

public File getDataFolder(Context context) {
    File dataDir = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            dataDir = new File(Environment.getExternalStorageDirectory(), "myappdata");
            if(!dataDir.isDirectory()) {
                dataDir.mkdirs();
            }
        }

        if(!dataDir.isDirectory()) {
            dataDir = context.getFilesDir();
        }

    return dataDir;
}

它将返回位于SD卡中名为“myappdata”的文件夹。之后,如果要从该文件夹加载图像,可以使用以下代码:

File cacheDir = getDataFolder(this);
File cacheFile = new File(cacheDir, "images.jpeg");
InputStream fileInputStream = new FileInputStream(cacheFile);
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inSampleSize = scale;
bitmapOptions.inJustDecodeBounds = false;
Bitmap wallpaperBitmap = BitmapFactory.decodeStream(fileInputStream, null, bitmapOptions);
ImageView imageView = (ImageView)this.findViewById(R.id.preview);
imageView.setImageBitmap(wallpaperBitmap);

如果您仍然遇到上述代码问题,可以在此处查看完整示例:

Android Save And Load Downloading File Locally