Android ImageView 显示本地图片

布局文件

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"> <ImageView
android:id="@+id/img"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:background="#aa111222"
android:onClick="getPicture"
/>
</RelativeLayout>

主文件

 package com.example.administrator.getpicture;

 import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView; import java.io.InputStream; public class MainActivity extends Activity { private ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView)this.findViewById(R.id.img);
}
//图片点击事件
public void getPicture(View v)
{
Intent intent = new Intent(Intent.ACTION_PICK,null);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
//intent 待启动的Intent 100(requestCode)请求码,返回时用来区分是那次请求
startActivityForResult(intent ,100);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//返回成功,请求码(对应启动时的requestCode)
if(resultCode == RESULT_OK && requestCode==100)
{
//方式一(不建议使用)
//下面的一句代码,也可以把图片显示在ImageView中
//但图片过大的时候,将无法显示,所以
//img.setImageURI(data.getData()); //方式二
Uri uri = data.getData();
ContentResolver cr = this.getContentResolver();
try {
//根据Uri获取流文件
InputStream is = cr.openInputStream(uri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize =3;
Bitmap bitmap = BitmapFactory.decodeStream(is,null,options);
img.setImageBitmap(bitmap);
}
catch(Exception e)
{
Log.i("lyf", e.toString());
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}

对了,别忘了加权限

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

希望可以帮到大家。

04-22 23:34