图片的二次采样是将从网络上获取到的原图,进行比例缩小,比如最常见的头像设置。不多说直接上代码。
主类代码:
Button btn;
ImageView img;
String str = "https://goss.veer.com/creative/vcg/veer/800water/veer-141874146.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_examday06);
//获取控件
btn = findViewById(R.id.btn);
img = findViewById(R.id.img);
//设置监听
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new MyAsync().execute(str);
}
});
}
异步处理下载图片并且二次处理
/**
* 异步下载图片
*/
class MyAsync extends AsyncTask<String,Object, Bitmap>{
@Override
protected void onPostExecute(Bitmap bitmap) {
img.setImageBitmap(bitmap);
super.onPostExecute(bitmap);
}
@Override
protected Bitmap doInBackground(String... strings) {
try {
URL u = new URL(strings[0]);
//创建连接
HttpURLConnection connection = (HttpURLConnection)u.openConnection();
//设置访问方式
connection.setRequestMethod("GET");
//连接
connection.connect();
//访问网页是否成功
if(connection.getResponseCode() == 200){
Log.e("###判断","进来了");
//字节流
InputStream is = connection.getInputStream();
//byte流
ByteArrayOutputStream os = new ByteArrayOutputStream();
//读取数据
int len = -1;
byte[] b = new byte[1024];
while((len = is.read(b))!=-1){
os.write(b,0,len);
Log.e("###byte",""+len);
}
is.close();
os.close();
byte[] bs = os.toByteArray();
//进行第一次采样
BitmapFactory.Options options = new BitmapFactory.Options();
//只拿边框
options.inJustDecodeBounds = true;
Log.e("###bs",bs.length+"");
//获取到原图
BitmapFactory.decodeByteArray(bs, 0, bs.length,options);
//拿到最初的宽和高
int height = options.outHeight;
int width = options.outWidth;
Log.e("###height",height+"");
int size = 1;//设置比例
while (height / size > 80||width / size > 80){
size *= 2;
Log.e("###size",size+"");
}
options.inJustDecodeBounds = false;
//设置比例
options.inSampleSize = size;
//重新设置 图片
Bitmap bitmap1 = BitmapFactory.decodeByteArray(bs, 0, bs.length, options);
Log.e("###返回","返回");
return bitmap1;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}