1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 public class MainActivity extends Activity { private ImageView lv; private WindowManager wm; private Point outSize; @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_main); lv = (ImageView) this .findViewById(R.id.lv); wm = (WindowManager) getSystemService(WINDOW_SERVICE); outSize = new Point(); } @Override protected void onActivityResult( int requestCode, int resultCode, Intent data) { Uri uri = data.getData(); try { InputStream stream = getContentResolver().openInputStream(uri); // 旧版的api int windowHeight = wm.getDefaultDisplay().getHeight(); int windowWidth = wm.getDefaultDisplay().getWidth(); BitmapFactory.Options opts = new Options(); // 设置 不去真正的解析位图 不把他加载到内存 只是获取这个图片的宽高信息 opts.inJustDecodeBounds = true ; // BitmapFactory.decodeFile("/sdcard/a.jpg", opts); BitmapFactory.decodeStream(stream, null , opts); int width = opts.outWidth; int height = opts.outWidth; if (width > windowWidth || height > windowHeight) { int x = width / windowWidth; int y = height / windowHeight; opts.inSampleSize = x > y ? x : y; } else { opts.inSampleSize = 1 ; } // 让位图工厂真正的去解析图片 opts.inJustDecodeBounds = false ; // 注意流的加载 需要重新加载流 stream = getContentResolver().openInputStream(uri); Bitmap bitmap = BitmapFactory.decodeStream(stream, null , opts); lv.setImageBitmap(bitmap); } catch (Exception e) { e.printStackTrace(); } super .onActivityResult(requestCode, resultCode, data); } public void click(View view) { Intent intent = new Intent(); intent.setAction( "android.intent.action.PICK" ); intent.addCategory( "android.intent.category.DEFAULT" ); intent.setType( "image/*" ); startActivityForResult(intent, 0 ); } }
来自为知笔记(Wiz)
转载于:https://www.cnblogs.com/feelbest/p/3696228.html
相关资源:android 加载本地图片