首页 > 其他分享 >Android中实现网络图片的获取

Android中实现网络图片的获取

时间:2023-06-02 18:02:09浏览次数:41  
标签:URL bm Bitmap 获取 msg import Android android 图片


在Android中要想获取网络资源,可以使用 HttpURLConnection 和 HttpsURLConnection 来实现相关功能。

下面案例实现了基于URL的简单请求响应,通过HttpURLConnection 获取连接,通过InputStream获取输入流,BitmapFactory 将数据流转换为 Bitmap,再将 Bitmap 通过线程的 Message发送出去,Handler 接收到消息就会通知 ImageView 显示出来。相关操作是通过点击按钮触发的。

接下来看相关代码的实现:

XML文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="获取图片"/>

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:layout_gravity="center"
        android:scaleType="fitXY" />
</LinearLayout>

java文件:

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    String path = "https://s1.ax1x.com/2020/05/05/YkGcqg.png";
    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.btn);
        imageView = (ImageView) findViewById(R.id.imageView);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Bitmap bm=getBitmap(path);
                        Message msg = new Message();
                        msg.what = 0;
                        msg.obj = bm;
                        System.out.println("000");
                        handle.sendMessage(msg);
                    }
                }).start();
            }
        });
    }

    //在消息队列中实现对控件的更改
    private Handler handle = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    System.out.println("111");
                    Bitmap bm=(Bitmap)msg.obj;
                    imageView.setImageBitmap(bm);
                    break;
            }
        };
    };

    private Bitmap getBitmap(String path) {
        Bitmap bm = null;
        try {
            URL url = new URL(path);//创建一个URL对象,其参数为网络图片的链接地址
            //使用一个URL对象开启一个链接
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            //设置相关参数
            con.setDoInput(true);
            con.setConnectTimeout(5000);//设置超时
            con.setReadTimeout(2000);
            con.connect();
            InputStream is = con.getInputStream();//获取输入流
            bm = BitmapFactory.decodeStream(is);//将输入流解码为Bitmap对象
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bm;
    }
}

在这里要 注意 的是,千万不要忘记要在 manifest 文件中添加下面一行代码

<uses-permission  android:name="android.permission.INTERNET" />

进行上网权限的添加,否则就无法获取网络资源。

运行后点击按钮实现效果:

Android中实现网络图片的获取_xml


注:
其中的链接是我的图床上的一张图片(https://s1.ax1x.com/2020/05/05/YkGcqg.png)


标签:URL,bm,Bitmap,获取,msg,import,Android,android,图片
From: https://blog.51cto.com/u_14458591/6404468

相关文章

  • c++ libcurl获取http header信息
    boolHttpDownloader::GetReceiveHeaderInfo(conststd::string&strUrl,std::map<std::string,std::string>&mapHeaderKeyValue){boolbRet=false;if(strUrl.empty()){returnbRet;}else{CURL*handl......
  • 使用Python爬虫爬取网络美女图片
    准备工作安装python3.6略安装requests库(用于请求静态页面)pipinstallrequests-ihttps://mirrors.ustc.edu.cn/pypi/web/simple安装lxml库(用于解析html文件)pipinstalllxml-ihttps://mirrors.ustc.edu.cn/pypi/web/simple安装与配置selenium(用于请求动态页面)pipinstall......
  • 6、如何获取配置中心的配置
    公众号:java乐园源码:https://gitee.com/hjj520/spring-cloud-2.x/在《配置中心》这一篇博文里学习了如何git获取配置文件。大概的流程可以用下图来概括。《配置中心》这篇博文说的是ConfigServer,本篇将和大家看看如何编写一个ConfigClient从ConfigServer获取配置。1、先在......
  • Android优秀开源项目
    203.208.46.146www.google.com74.125.113.121developer.android.com203.208.46.146dl.google.com203.208.46.146dl-ssl.google.comAndroid经典的开源项目其实非常多,但是国内的博客总是拿着N年前的一篇复制来复制去,实在是不利于新手学习。今天爬爬把自己熟悉的一些开源......
  • JAVA通过oshi获取系统和硬件信息
    JAVA通过oshi获取系统和硬件信息 一、引入jar包本项目主要使用第开源jar包:https://github.com/oshi/oshi<dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>RELEASE</vers......
  • Android 的一些提示框
    1.在测试时,如何实现一个提示可以使用Toast.makeText(this,"这是一个提示",Toast.LENGTH_SHORT).show();//从资源文件string.xml里面取提示信息Toast.makeText(this,getString(R.string.welcome),Toast.LENGTH_SHORT).show();这个提示会几秒钟后消失2.可以使用AlertDialog......
  • 直播电商平台开发,RecyclerView实现item图片放大缩小
    直播电商平台开发,RecyclerView实现item图片放大缩小((ShopDetailsViewHolder)holder).img_list.setOnClickListener(newView.OnClickListener(){  @RequiresApi(api=Build.VERSION_CODES.LOLLIPOP)  @Override  publicvoidonClick(Viewv){    Inten......
  • group by 获取最新的数据
    SELECT *FROMxxxAStWHERE 1=1 ANDt.idIN( selectidFROM( SELECT MAX(t.id)id FROM xxxASt WHERE 1=1 GROUPBY t.id_number, t.`class` ORDERBY t.id LIMIT0, 10)a ) ORDERBY t.id LIMIT0, 10......
  • Android 12 Window ViewRootImpl Activity的关系
    1Window和ViewRootImpl有什么关系?看右侧流程图,上层的UI大体分成两大类,一是Activity,另一类是CustomWindow(如状态栏、toast等)。但是他们都要经过WindowManager.addView这个接口添加到系统中。经过WindowManagerGlobal,会new一个ViewRootImpl,ViewRootImpl会申请server端的Sessio......
  • Android strings.xml按照key修改
    strings.xml匹配替换将两个Android项目中的多语言字符串文件(strings.xml)进行比较,如果其中一个项目中包含另一个项目没有的字符,则合并到单一的输出文件,并以key在原始XML文件中更新value值。如果key匹配不准确则忽略它。具体来说:引入re,xml.etree.ElementTree和argpar......