Android ImageView 显示本地图片
布局文件
1 <?xml version="1.0" encoding="utf-8"?> 2 <RelativeLayout 3 xmlns:android="http://schemas.android.com/apk/res/android" 4 xmlns:tools="http://schemas.android.com/tools" 5 android:layout_width="match_parent" 6 android:layout_height="match_parent" 7 tools:context=".MainActivity"> 8 9 <ImageView 10 android:id="@+id/img" 11 android:layout_width="200dp" 12 android:layout_height="200dp" 13 android:layout_centerHorizontal="true" 14 android:layout_marginTop="50dp" 15 android:background="#aa111222" 16 android:onClick="getPicture" 17 /> 18 </RelativeLayout>
主文件
1 package com.example.administrator.getpicture; 2 3 import android.app.Activity; 4 import android.content.ContentResolver; 5 import android.content.Intent; 6 import android.graphics.Bitmap; 7 import android.graphics.BitmapFactory; 8 import android.net.Uri; 9 import android.os.Bundle; 10 import android.provider.MediaStore; 11 import android.util.Log; 12 import android.view.View; 13 import android.widget.ImageView; 14 15 import java.io.InputStream; 16 17 public class MainActivity extends Activity { 18 19 private ImageView img; 20 @Override 21 protected void onCreate(Bundle savedInstanceState) { 22 super.onCreate(savedInstanceState); 23 setContentView(R.layout.activity_main); 24 img = (ImageView)this.findViewById(R.id.img); 25 } 26 //图片点击事件 27 public void getPicture(View v) 28 { 29 Intent intent = new Intent(Intent.ACTION_PICK,null); 30 intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*"); 31 //intent 待启动的Intent 100(requestCode)请求码,返回时用来区分是那次请求 32 startActivityForResult(intent ,100); 33 } 34 @Override 35 protected void onActivityResult(int requestCode, int resultCode, Intent data) { 36 //返回成功,请求码(对应启动时的requestCode) 37 if(resultCode == RESULT_OK && requestCode==100) 38 { 39 //方式一(不建议使用) 40 //下面的一句代码,也可以把图片显示在ImageView中 41 //但图片过大的时候,将无法显示,所以 42 //img.setImageURI(data.getData()); 43 44 //方式二 45 Uri uri = data.getData(); 46 ContentResolver cr = this.getContentResolver(); 47 try { 48 //根据Uri获取流文件 49 InputStream is = cr.openInputStream(uri); 50 BitmapFactory.Options options = new BitmapFactory.Options(); 51 options.inSampleSize =3; 52 Bitmap bitmap = BitmapFactory.decodeStream(is,null,options); 53 img.setImageBitmap(bitmap); 54 } 55 catch(Exception e) 56 { 57 Log.i("lyf", e.toString()); 58 } 59 } 60 super.onActivityResult(requestCode, resultCode, data); 61 } 62 }
对了,别忘了加权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
希望可以帮到大家。