public void loaderPic(View view){
//第一种方式:
//readNetPic();
//第二种方式
readNetPic("http://i3.s2.dpfile.com/2010-12-20/6201691_b.jpg(249x249)/thumb.jpg");
}
//读取网络资源
public void readNetPic(String Path){
new AsyncTask(){
@Override
protected void onPostExecute(Bitmap bitmap) {
if(bitmap!=null){
pic.setImageBitmap(bitmap);
}else {
pic.setImageResource(R.mipmap.ic_launcher);
}
}
@Override
protected Bitmap doInBackground(String... params) {
try {
URL url = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
if(connection.getResponseCode()==200){
InputStream is = connection.getInputStream();
return picResizer(url,is,50,50);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}.execute(Path);
}
//压缩图片
public Bitmap picResizer(URL url,InputStream is,int requestWidth,int requestHeight){
try {
//只需解析图片的宽高
BitmapFactory.Options options = new BitmapFactory.Options();
BitmapFactory.decodeStream(is, null, options);
//假解析图片
options.inJustDecodeBounds = true;
//调用采样率
int sampleSize = reducePic(options,requestWidth,requestHeight);
//重新为字段赋值
options.inSampleSize = sampleSize;
is.close();
is = url.openStream();
//真解析图片
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeStream(is, null, options);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//计算采样率
public int reducePic(BitmapFactory.Options options,int requestWidth,int requestHeight){
//得到原始图片的宽高
int width = options.outWidth;
int height = options.outHeight;
//定义一个变量 采样率
int sampleSize = 1;
//requestWidth与requestHeight是期望的宽高
if(width>requestWidth || height>requestHeight){
int halfWidth = width/2;
int halfHeight = height/2;
//计算采样率
while((halfHeight/sampleSize) > requestHeight && (halfWidth/sampleSize) > requestWidth){
sampleSize *=2;
}
}
//返回采样率
return sampleSize;
}
()