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

本文介绍如何在Android应用中使用BitmapFactory.decodeFile()方法从手机磁盘加载图片到ImageView。通过创建BitmapFactoryDeocdeFileActivity,设置布局包含Button和ImageView,点击Button后实现图片的显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

加载手机磁盘里的图片文件(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 Activity implements

       OnClickListener {

    private Button btn = null;

    private ImageView image = 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);

       }

    }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值