也是直接上代码吧
1 package cn.itcast.resizeimage;
2
3 import java.io.FileNotFoundException;
4 import java.io.IOException;
5 import java.io.InputStream;
6
7 import android.app.Activity;
8 import android.content.Intent;
9 import android.graphics.Bitmap;
10 import android.graphics.BitmapFactory;
11 import android.graphics.BitmapFactory.Options;
12 import android.net.Uri;
13 import android.os.Bundle;
14 import android.view.Display;
15 import android.view.View;
16 import android.view.WindowManager;
17 import android.widget.ImageView;
18
19 public class LoadImageActivity extends Activity {
20 private ImageView iv;
21 private WindowManager wm;
22 private Display display;
23 @Override
24 public void onCreate(Bundle savedInstanceState) {
25 super.onCreate(savedInstanceState);
26 setContentView(R.layout.main);
27 iv = (ImageView) findViewById(R.id.iv);
28 wm = getWindowManager();
29 //获取手机的屏幕宽高30 display = wm.getDefaultDisplay();
31 }
32
33 public void selectImage(View view) {
34 Intent intent = new Intent();
35 intent.setAction("android.intent.action.PICK");
36 intent.addCategory("android.intent.category.DEFAULT");
37 intent.setType("image/*");
38 startActivityForResult(intent, 0);
39
40 }
41
42 @Override
43 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
44 try {
45 if (data != null) {
46 // 得到点击图片的uri47 Uri uri = data.getData();
48 //对 要加载的图片进行缩放
49 //1.得到图片的宽度和高度.
50 //由于我们只想得到图片的宽度和高度,这个时候 只需要解析图片的头信息51 BitmapFactory.Options opts = new Options();
52 opts.inJustDecodeBounds = true;//让 bimapfactory假的解析这个位图,只获取位图的边框信息53 InputStream is = getContentResolver().openInputStream(uri);
54 BitmapFactory.decodeStream(is);
55
56 int bitmapHeight = opts.outHeight;
57 int bitmapWidth = opts.outWidth;
58
59 int windowHeight = display.getHeight();
60 int windowWidth = display.getWidth();
61 //获取水平和垂直方向的缩放比62 int scaley = bitmapHeight / windowHeight;
63 int scalex = bitmapWidth / windowWidth;
64 if(scalex>scaley&&scaley>1){
65 opts.inSampleSize = scalex;
66 }
67 if(scaley>scalex&&scalex>1){
68 opts.inSampleSize = scaley;
69 }
70 opts.inJustDecodeBounds = false;// 由于已经得到了缩放比例 ,让位图工厂真正的解析这个位图
71 // 由于前面 我们已经解析了这个输入流, 需要重新初始化这个输入流72 is = getContentResolver().openInputStream(uri);
73 Bitmap bitmap = BitmapFactory.decodeStream(is);
74
75
76
77 iv.setImageBitmap(bitmap);
78 }
79 } catch (Exception e) {
80 e.printStackTrace();
81 }
82 super.onActivityResult(requestCode, resultCode, data);
83 }
84 }
当前题目:根据屏幕分辨率缩放显示图片-创新互联
文章链接:
http://cdweb.net/article/eepjs.html