1:创建工具类,用来计算采样率
public class ImageResizer {
/**
* 计算采样率
* @param options
* @param requestWidth
* @param requestHeight
* @return
*/
public static int calculateInSampleSize(BitmapFactory.Options options,int requestWidth,int requestHeight){
//获取图片的真实的宽高
int width = options.outWidth;
int height = options.outHeight;
int inSampleSize = 1;
options.inSampleSize = inSampleSize;//默认 1 1代表不对图片进行任何压缩
//计算采样率
if(width > requestWidth || height > requestHeight){
int halfWidth = width / 2;
int halfHeight = height / 2;
while((halfWidth / inSampleSize) >= requestWidth &&
(halfHeight / inSampleSize) >= requestHeight){
//计算采样率
inSampleSize *= 2;
}
}
return inSampleSize;
}
}
2:调用
下面是在AsyncTask方法里调用的该工具类注意doInBackground方法即可
public class MainActivity extends AppCompatActivity {
private ImageView ivIcon;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ivIcon = (ImageView) findViewById(R.id.ivIcon);
}
public void btnLoadImge(View v){
loadImage("http://20.1.4.181:8080/beautiful.jpg",100,100);
}
/**
* 加载图片,并压缩
* @param imgPath
* @param requestWidth
* @param requestHeight
*/
public void loadImage(String imgPath, final int requestWidth, final int requestHeight){
new AsyncTask<String,Void,Bitmap>(){
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if(bitmap != null){
ivIcon.setImageBitmap(bitmap);
}
}
@Override
protected Bitmap doInBackground(String... params) {
try {
//得到图片路径
String path = params[0];
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.setDoInput(true);
connection.setDoOutput(true);
int code = connection.getResponseCode();
if(code == 200){
//得到图片流
InputStream is = connection.getInputStream();
//解析图片
BitmapFactory.Options options = new BitmapFactory.Options();
//让图片暂时不去解析 只需要获取图片的宽高
options.inJustDecodeBounds = true;
//解析一下图片,这个时候,只会解析图片的宽*高
BitmapFactory.decodeStream(is,null,options);
//计算采样率
options.inSampleSize = ImageResizer.calculateInSampleSize(options,requestWidth,requestHeight);
//我这时候需要真正去解析图片
options.inJustDecodeBounds = false;
//关闭流
is.close();
//得到图片的输入流
is = url.openStream();
//解析图片的时候,才会去真正解析
Bitmap bitmap = BitmapFactory.decodeStream(is,null,options);
//关闭流
is.close();
return bitmap;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}.execute(imgPath);
}
}