从SD卡读图并显示(一)

来源:互联网 发布:淘宝html5 编辑:程序博客网 时间:2024/05/28 18:45

本节,我们做一个很简单的Demo,实现从SD卡读取一张图片,并把它显示在APP中。

分三步:
1.设置权限。
在Manifest文件中添加三行权限信息。

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

2.配置MXL视图。
可以参考:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <ImageView        android:id="@+id/myView"        android:layout_width="fill_parent"        android:layout_height="fill_parent"        /></LinearLayout>

3.Java代码编写部分。
大体上就两个步骤:获取图片文件,显示图片
(详细过程见代码,注释)

package com.example.showimage;import android.app.Activity;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Bundle;import android.os.Environment;import android.widget.ImageView;public class MainActivity extends Activity { private ImageView myView = null;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        myView = (ImageView)findViewById(R.id.myView);        String path = Environment.getExternalStorageDirectory() + "/";//Get the SD card default path        String name = path + "image.jpg";//Get the image File's path+name        BitmapFactory.Options option = new BitmapFactory.Options();        option.inSampleSize = 10;//Set the different pixel.The bigger,the lower        Bitmap bm = BitmapFactory.decodeFile(name,option);//Decode the image file according to the pathName and the pixel        myView.setImageBitmap(bm);//Let the ImageView myView equal to the bitmap    }}

注意:myView.setImageBitmap(bm); 是在代码中设置xml中的id属性。(因为此刻图片资源并不来自app本身(或者说R资源),是来自SD卡。)

点击这里下载源代码

0 0
原创粉丝点击