1 package com.itheima.getimage; 2 3 import android.app.Activity; 4 import android.content.Intent; 5 import android.database.Cursor; 6 import android.graphics.Bitmap; 7 import android.graphics.BitmapFactory; 8 import android.graphics.BitmapFactory.Options; 9 import android.net.Uri; 10 import android.os.Bundle; 11 import android.view.View; 12 import android.view.WindowManager; 13 import android.widget.ImageView; 14 15 public class MainActivity extends Activity { 16 17 private ImageView iv; 18 19 @Override 20 protected void onCreate(Bundle savedInstanceState) { 21 super.onCreate(savedInstanceState); 22 setContentView(R.layout.activity_main); 23 24 iv = (ImageView) findViewById(R.id.iv); 25 } 26 27 public void open(View v) { 28 Intent intent = new Intent(Intent.ACTION_PICK); 29 intent.setType("image/*"); 30 startActivityForResult(intent, 100); 31 } 32 33 @Override 34 protected void onActivityResult(int requestCode, int resultCode, Intent intent) { 35 Uri uri = intent.getData(); 36 String path = getAbsolutePath(uri); 37 Bitmap bm = getUsableBitmap(path); 38 iv.setImageBitmap(bm); 39 System.out.println(bm.getWidth() + ", " + bm.getHeight()); 40 } 41 42 public String getAbsolutePath(Uri uri) { 43 Cursor c = getContentResolver().query(uri, new String[] { "_data" }, null, null, null); 44 c.moveToNext(); 45 return c.getString(0); 46 } 47 48 @SuppressWarnings("deprecation") 49 private Bitmap getUsableBitmap(String path) { 50 Options opts = new Options(); 51 opts.inJustDecodeBounds = true; // 设置只加载图片大小 52 BitmapFactory.decodeFile(path, opts); 53 54 WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE); 55 int width = manager.getDefaultDisplay().getWidth(); // 屏幕宽度 56 int height = manager.getDefaultDisplay().getHeight(); // 屏幕高度 57 58 int xScale = opts.outWidth / width; 59 int yScale = opts.outHeight / height; 60 int scale = xScale > yScale ? xScale : yScale; // 计算缩放比例 61 62 opts.inJustDecodeBounds = false; // 设置不只加载图片大小 63 opts.inSampleSize = scale; // 设置缩放比例 64 return BitmapFactory.decodeFile(path, opts); // 按照设置加载图片(缩放) 65 } 66 67 } 68