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 btnImageResizer(View view){
//loadImage("http://tnfs.tngou.net/image/info/150822/d35a601b668c160a07c43d4925af9007.jpg");
loadImage2("http://tnfs.tngou.net/image/info/150822/d35a601b668c160a07c43d4925af9007.jpg");
}
private void loadImage(String url){
new AsyncTask<String,Void,Bitmap>(){
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
//主线程
if(bitmap != null){
ivIcon.setImageBitmap(bitmap);
}else{
ivIcon.setBackgroundResource(R.mipmap.ic_launcher_round);
}
}
@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);
//等待服务器响应
int code = connection.getResponseCode();
if(code == 200){
InputStream is = connection.getInputStream();
BitmapFactory.Options options = new BitmapFactory.Options();
//首先不要对图片进行真正解析,只需要假解析(只需要得到图片的宽高)
//inJustDecodeBounds = true BitmapFactory不会去真正解析这张图片的数据
//只会解析这张图片的宽高
options.inJustDecodeBounds = true;
//options 多个选项
BitmapFactory.decodeStream(is,null,options);
//得到图片宽高
int width = options.outWidth;
int height = options.outHeight;
//System.out.println("宽 : "+width+" 高 : "+height);
//定义变量记住采样率信息
int inSampleSize = 1;//1 默认不对图片进行任何的压缩
if(width > 100 || height > 100){
int halfWidth = width / 2;//640 / 2 = 320
int halfHeight = height / 2;
//计算采样率
while ((halfWidth / inSampleSize) >= 100 && (halfHeight / inSampleSize) >= 100){
inSampleSize *= 2;
}
}
//真正解析图片
options.inSampleSize = inSampleSize;
//inJustDecodeBounds = false 图片工厂会去对图片真正解析
options.inJustDecodeBounds = false;
//转换不出来图片的原因是系统方法Bug
//避免这个bug好的方法:将之前获取的图片流关闭
is.close();
//通过url对象重新得到图片流
is = url.openStream();
Bitmap bitmap = BitmapFactory.decodeStream(is,null,options);
//Bitmap bitmap = BitmapFactory.decodeStream(is);
is.close();
return bitmap;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}.execute(url);
}