public class MainActivity extends AppCompatActivity {
private ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//找到控件
img = (ImageView) findViewById(R.id.img);
}
public void btnLoadImage(View view){
getLoadiImg("http://tnfs.tngou.net/image/info/150912/6f1f81106d337d769882e34f481cc191.jpg");
}
private void getLoadiImg(String url){
new AsyncTask(){
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if (bitmap != null){
img.setImageBitmap(bitmap);
}else {
img.setImageResource(R.mipmap.ic_launcher_round);
}
}
@Override
protected Bitmap doInBackground(String... strings) {
try {
//得到请求地址
String path = strings[0];
URL url = new URL(path);
//打开链接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//设置请求方式get
connection.setRequestMethod("GET");
//设置打开链接的时间
connection.setConnectTimeout(5000);
//设置读取数据返回的时间
connection.setReadTimeout(5000);
//得到状态码
int code = connection.getResponseCode();
if (code == 200){
InputStream is = connection.getInputStream();
return getBitmap(is,url,100,100);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}.execute(url);
}
private Bitmap getBitmap(InputStream is,URL url,int requsetHeight,int requsetWidth){
try {
//将字节流转化成图片对象
//得到图片的宽高
BitmapFactory.Options options = new BitmapFactory.Options();
//假解析图片
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is,null,options);
//得到采样率
int inSampleSize = getinSampleSize(options, requsetHeight, requsetWidth);
//将得到的采样率赋值
options.inSampleSize = inSampleSize;
//得到采样率后进行真解析
options.inJustDecodeBounds = false;
//重新打开流
is.close();
InputStream inputStream = url.openStream();
//得到压缩后的图片
Bitmap bitmap = BitmapFactory.decodeStream(inputStream,null,options);
return bitmap;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private int getinSampleSize(BitmapFactory.Options options,int requsetHeight,int requsetWidth){
//得到图片的原始宽高
int height = options.outHeight;
int width = options.outWidth;
//定义一个变量记录采样率
int inSampleSize = 1;
//判断是否在期望的宽高内
if (height > requsetHeight || width > requsetWidth){
int helfHeight = height / 2;
int helfWidth = width /2;
//计算采样率
while (helfHeight/inSampleSize > requsetHeight && helfWidth/inSampleSize >requsetWidth){
inSampleSize *= 2;
}
}
return inSampleSize;
}
}
压缩图片
最新推荐文章于 2022-09-01 11:08:00 发布