加载手机磁盘里的图片文件(BitmapFactory.decodeFile()

来源:互联网 发布:咸鱼搜索知乎 编辑:程序博客网 时间:2024/05/15 00:23

加载手机磁盘里的图片文件(BitmapFactory.decodeFile()

新建一个继承Activity类的BitmapFactoryDeocdeFileActivity,并设置布局文件为:bitmapdecodefile.xml。

在布局文件中添加一个Button和一个ImageView组件

    <Button

        android:id="@+id/bitmapfactorydecodefile_btn"

        style="@android:style/Widget.Button.Inset"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="@string/change"/>

 

 

    <ImageView

        android:id="@+id/bitmapfactorydecodefile_image"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_gravity="center"/>

而后在代码中实现点击后打开一张手机里面的图片

package lyx.feng.second;

......

public class BitmapFactoryDeocdeFileActivity extends Activityimplements

       OnClickListener {

    private Buttonbtn = null;

    private ImageViewimage = null;

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

       super.setContentView(R.layout.bitmapdecodefile);

       // 取得组件,注册按钮事件

       this.btn = (Button)super

              .findViewById(R.id.bitmapfactorydecodefile_btn);

       this.image = (ImageView)super

              .findViewById(R.id.bitmapfactorydecodefile_image);

       this.btn.setOnClickListener(this);

    }

 

    @Override

    public void onClick(View v) {

       // 得到一个图片用于保存到内存中

       Bitmap bitmap = BitmapFactory.decodeResource(getResources(),

              R.drawable.icon_002);

       File file = new File("data/data/lyx.feng.simpletextdemo/image.png");

       if (!file.exists()) {

           // 如果文件不存在就保存一张图片到File

           try {

              FileOutputStream stream = new FileOutputStream(file);

              bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);

           } catch (FileNotFoundException e) {

              e.printStackTrace();

           }

       } else {

           bitmap = null;

           // 读取图片到ImageView

           bitmap = BitmapFactory

                  .decodeFile("data/data/lyx.feng.simpletextdemo/image.png");

           this.image.setImageBitmap(bitmap);

       }

    }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

0 0
原创粉丝点击