压缩图片


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;
}




}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值