加载本地图片使用BitmapFactory.decodeFile
加载网络图片使用BitmapFactory.decodeStream
Options opts = new Options(); opts.inJustDecodeBounds = true;// BitmapFactory.decodeStream(is, null, opts);
Options opts = new Options();
opts.inJustDecodeBounds = true; //设置为true, 加载器不会返回图片, 而是设置Options对象中以out开头的字段.即仅仅解码边缘区域
BitmapFactory.decodeFile(filePath, opts);
// 得到图片的宽和高
int imageWidth = opts.outWidth;
int imageHeight = opts.outHeight;
// 获取屏幕的宽和高
Display display = this.getWindowManager().getDefaultDisplay(); // 获取默认窗体显示的对象
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
// 计算缩放比例
int widthScale = imageWidth / screenWidth;
int heightScale = imageHeight / screenHeight;
int scale = widthScale > heightScale ? widthScale:heightScale;
// 指定加载可以加载出图片.
opts.inJustDecodeBounds = false;
// 使用计算出来的比例进行缩放
opts.inSampleSize = scale;
Bitmap bm = BitmapFactory.decodeFile(path, opts);
/** * 计算图片的缩放比例 * @return */ public int getScare() { try { HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(imageUrl); HttpResponse response = client.execute(httpGet); int code = response.getStatusLine().getStatusCode(); if (200 == code) { InputStream is = response.getEntity().getContent(); Options opts = new Options(); opts.inJustDecodeBounds = true; BitmapFactory.decodeStream(is, null, opts); int imageWidth = opts.outWidth; int imageHeight = opts.outHeight; Display display = ImageActivity.this.getWindowManager() .getDefaultDisplay(); int screenWidth = display.getWidth(); int screenHeight = display.getHeight(); int widthscale = imageWidth / screenWidth; int heightscale = imageHeight / screenHeight; int scale = widthscale > heightscale ? widthscale : heightscale; return scale; } } catch (Exception e) { e.printStackTrace(); } return 1;//网络连接失败时默认返回1 }
/** * 获取网络图片 */ protected void getNetImage() { try { HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(imageUrl); HttpResponse response = client.execute(httpGet); int code = response.getStatusLine().getStatusCode(); if (200 == code) { InputStream is = response.getEntity().getContent(); Options opts = new Options(); //根据计算出的比例进行缩放 int scale = getScare(); opts.inSampleSize = scale; Bitmap bm = BitmapFactory.decodeStream(is, null, opts); //将bm发生给主线程用于显示图片,更新UI Message msg = Message.obtain(); msg.obj = bm; handler.sendMessage(msg); } } catch (Exception e) { e.printStackTrace(); } }
//显示图片 Handler handler = new Handler() { public void handleMessage(Message msg) { Bitmap bm = (Bitmap) msg.obj; iv.setImageBitmap(bm); }; };