您的位置:首页 > 移动开发 > Android开发

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

2016-03-08 22:53 465 查看

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

 

 

 

 

 

 

 

 

 

 

 

 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息