1. 圖片網址url轉化為bitmap
1.1. 方法一 通過 HttpURLConnection 請求
??要使用一個線程去訪問,因為是網絡請求,這是一個一步請求,不能直接返回獲取,要不然永遠為null,在這里得到BitMap之后記得使用Hanlder或者EventBus傳回主線程,不過現在加載圖片都是用框架了,很少有轉化為Bitmap的需求
/*** 通過 網絡圖片 url 獲取圖片 Bitmap* @param photoUrl 網絡圖片 url*/private void requestWebPhotoBitmap(String photoUrl) {new Thread(() -> {HttpURLConnection connection = null;try {URL bitmapUrl = new URL(photoUrl);connection = (HttpURLConnection) bitmapUrl.openConnection();connection.setRequestMethod("GET");connection.setConnectTimeout(5000);connection.setReadTimeout(5000);// 判斷是否請求成功if (connection.getResponseCode() == 200) {Message hintMessage = new Message();hintMessage.what = HANDLER_START_DOWNLOAD;hintHandler.sendMessage(hintMessage);InputStream inputStream = connection.getInputStream();imgBitmap = BitmapFactory.decodeStream(inputStream);Message message = showHandler.obtainMessage();showHandler.sendMessage(message);} else {Message hintMessage = new Message();hintMessage.what = HANDLER_NET_ERROR;hintHandler.sendMessage(hintMessage);}} catch (IOException e) {e.printStackTrace();} finally {if (connection != null) connection.disconnect();}}).start();}/*** 設置提示*/private final Handler hintHandler = new Handler(Looper.getMainLooper()){@Overridepublic void handleMessage(Message msg) {if(msg.what == HANDLER_START_DOWNLOAD)Toast.makeText(MainActivity.this, "獲取圖片中,請稍等", Toast.LENGTH_SHORT).show();else if(msg.what == HANDLER_NET_ERROR)Toast.makeText(MainActivity.this, "網絡錯誤,請重試", Toast.LENGTH_SHORT).show();}};/*** 展示圖片*/@SuppressLint("HandlerLeak")private final Handler showHandler = new Handler(Looper.getMainLooper()) {@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);ivPhoto.setImageBitmap(imgBitmap); //填充控件}};
1.2. 方法二 通過 Glide
1.2.1. java
/*** 獲取 網絡圖片 Bitmap* @param imgUrl 網絡圖片url*/private void requestWebPhotoBitmap(String imgUrl) {Toast.makeText(MainActivity.this, "獲取圖片中,請稍等", Toast.LENGTH_SHORT).show();Glide.with(MainActivity.this).asBitmap().load(imgUrl).into(new CustomTarget<Bitmap>() {@SuppressLint("ClickableViewAccessibility")@Overridepublic void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {imgBitmap = resource;ivPhoto.setImageBitmap(imgBitmap)}@Overridepublic void onLoadCleared(@Nullable Drawable placeholder) {}});}
1.2.2. kotlin
Glide.with(this).asBitmap().load(paramBean.userImg).into(object : CustomTarget<Bitmap?>() {override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap?>?) {val bitmap = resource}override fun onLoadCleared(placeholder: Drawable?) {}})
1.3. 調用
private Bitmap imgBitmap = null;private ImageView ivPhoto;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);ivPhoto = (ImageView) findViewById(R.id.photo);String imgUrl = "https://w.wallhaven.cc/full/l3/wallhaven-l3xk6q.jpg";requestWebPhotoBitmap(imgUrl);}