从SD卡读图并显示(一)

本节,我们做一个很简单的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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值