码迷,mamicode.com
首页 > 其他好文 > 详细

从SD卡读图并显示(一)

时间:2015-07-23 23:56:21      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:android

本节,我们做一个很简单的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卡。)

点击这里下载源代码

版权声明:本文为博主原创文章,未经博主允许不得转载。

从SD卡读图并显示(一)

标签:android

原文地址:http://blog.csdn.net/qq_16912257/article/details/47029291

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!