• Android | 通过URL获取网络图片Bitmap格式


    一、获取网络图片URL

            1.随便找一张网络图片   

            2.右键打开图像

            3.复制图片URL (.jpg或者其他图像格式结尾的url才是图片的url(统一资源定位器)啊 =>=)

    二、代码

            1.初始化绑定视图

    1. private Bitmap imgBitmap = null;
    2. private ImageView ivPhoto;
    3. @Override
    4. public void onCreate(Bundle savedInstanceState) {
    5. super.onCreate(savedInstanceState);
    6. setContentView(R.layout.activity_main);
    7. ivPhoto = (ImageView) findViewById(R.id.photo);
    8. String imgUrl = "https://w.wallhaven.cc/full/l3/wallhaven-l3xk6q.jpg";
    9. requestWebPhotoBitmap(imgUrl);
    10. }

            2.网络请求(核心代码)

                     (方法一 :通过 HttpURLConnection 请求)

    1. /**
    2. * 通过 网络图片 url 获取图片 Bitmap
    3. * @param photoUrl 网络图片 url
    4. */
    5. private void requestWebPhotoBitmap(String photoUrl) {
    6. new Thread(() -> {
    7. HttpURLConnection connection = null;
    8. try {
    9. URL bitmapUrl = new URL(photoUrl);
    10. connection = (HttpURLConnection) bitmapUrl.openConnection();
    11. connection.setRequestMethod("GET");
    12. connection.setConnectTimeout(5000);
    13. connection.setReadTimeout(5000);
    14. // 判断是否请求成功
    15. if (connection.getResponseCode() == 200) {
    16. Message hintMessage = new Message();
    17. hintMessage.what = HANDLER_START_DOWNLOAD;
    18. hintHandler.sendMessage(hintMessage);
    19. InputStream inputStream = connection.getInputStream();
    20. imgBitmap = BitmapFactory.decodeStream(inputStream);
    21. Message message = showHandler.obtainMessage();
    22. showHandler.sendMessage(message);
    23. } else {
    24. Message hintMessage = new Message();
    25. hintMessage.what = HANDLER_NET_ERROR;
    26. hintHandler.sendMessage(hintMessage);
    27. }
    28. } catch (IOException e) {
    29. e.printStackTrace();
    30. } finally {
    31. if (connection != null) connection.disconnect();
    32. }
    33. }).start();
    34. }
    35. /**
    36. * 设置提示
    37. */
    38. private final Handler hintHandler = new Handler(Looper.getMainLooper()){
    39. @Override
    40. public void handleMessage(Message msg) {
    41. if(msg.what == HANDLER_START_DOWNLOAD)
    42. Toast.makeText(MainActivity.this, "获取图片中,请稍等", Toast.LENGTH_SHORT).show();
    43. else if(msg.what == HANDLER_NET_ERROR)
    44. Toast.makeText(MainActivity.this, "网络错误,请重试", Toast.LENGTH_SHORT).show();
    45. }
    46. };
    47. /**
    48. * 展示图片
    49. */
    50. @SuppressLint("HandlerLeak")
    51. private final Handler showHandler = new Handler(Looper.getMainLooper()) {
    52. @Override
    53. public void handleMessage(Message msg) {
    54. super.handleMessage(msg);
    55. ivPhoto.setImageBitmap(imgBitmap); //填充控件
    56. }
    57. };

                    (方法二 : 通过 Glide)

    1. /**
    2. * 获取 网络图片 Bitmap
    3. * @param imgUrl 网络图片url
    4. */
    5. private void requestWebPhotoBitmap(String imgUrl) {
    6. Toast.makeText(MainActivity.this, "获取图片中,请稍等", Toast.LENGTH_SHORT).show();
    7. Glide.with(MainActivity.this).asBitmap().load(imgUrl).into(new CustomTarget() {
    8. @SuppressLint("ClickableViewAccessibility")
    9. @Override
    10. public void onResourceReady(@NonNull Bitmap resource, @Nullable Transitionsuper Bitmap> transition) {
    11. imgBitmap = resource;
    12. ivPhoto.setImageBitmap(imgBitmap)
    13. }
    14. @Override
    15. public void onLoadCleared(@Nullable Drawable placeholder) {
    16. }
    17. });
    18. }

            注意:使用 glide 要在 build.gradle(app)导包

        implementation 'com.github.bumptech.glide:glide:4.11.0'

            3.布局文件

    1. "1.0" encoding="utf-8"?>
    2. <FrameLayout
    3. xmlns:android="http://schemas.android.com/apk/res/android"
    4. android:layout_width="fill_parent"
    5. android:layout_height="fill_parent"
    6. android:layout_gravity="center" >
    7. <ImageView
    8. android:id="@+id/photo"
    9. android:layout_width="match_parent"
    10. android:layout_height="500dp"
    11. android:layout_gravity="center"
    12. android:scaleType="centerInside" >
    13. ImageView>
    14. FrameLayout>

    三、效果

  • 相关阅读:
    [附源码]java毕业设计社团管理系统
    基于Material Design风格开源、易用、强大的WPF UI控件库
    【概念】数据仓库和数仓建模
    数据结构与算法复习:第六弹
    时代潮流-云原生数据库的崛起
    react&antd问题(4)
    Python初体验
    8.26 Day44---项目部署
    CRF&HMM模型——理论
    电子学会 2023年3月 青少年软件编程Python编程等级考试三级真题解析(选择题+判断题+编程题)
  • 原文地址:https://blog.csdn.net/sun80760/article/details/126680156