获取网络上的图片,并显示在界面上的简单实现

布局文件如下:

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

    <EditText
        android:id="@+id/et_main_netpass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="请输入地址"
        android:text="https://www.baidu.com/img/bd_logo1.png"/>

    <Button
        android:id="@+id/bt_main_see"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="查看图片"/>

    <ImageView
        android:id="@+id/iv_main_showimage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

在AndroidManifest文件中添加网络访问权限;

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

实现代码如下:

package cn.test.ning.netimageview;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends Activity {
    private static final int UPDATE = 0;
    private EditText et_main_netpass;
    private ImageView iv_main_showimage;
    private Button bt_main_see;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE: {
                    Bitmap bitmap = (Bitmap) msg.obj;
                    iv_main_showimage.setImageBitmap(bitmap);
                    break;
                }
                default:
                    break;
            }
        }
    };

    private void initView() {
        setContentView(R.layout.activity_main);
        et_main_netpass = (EditText) this.findViewById(R.id.et_main_netpass);
        iv_main_showimage = (ImageView) this.findViewById(R.id.iv_main_showimage);
        bt_main_see = (Button) this.findViewById(R.id.bt_main_see);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initEvent();
    }

    private void initEvent() {
        bt_main_see.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String path = et_main_netpass.getText().toString().trim();
                if (TextUtils.isEmpty(path)) {//检测路径是否合法
                    Toast.makeText(MainActivity.this, "路径为空", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    //从缓存中取出图片,并显示在界面中
                    File file = new File(getCacheDir(), Base64.encodeToString(path.getBytes(), Base64.DEFAULT));
                    if (file.exists() && file.length() > 0) {
                        Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
                        iv_main_showimage.setImageBitmap(bitmap);
                        Toast.makeText(MainActivity.this, "get image form cache", Toast.LENGTH_SHORT).show();

                    } else {
                        new Thread() {
                            @Override
                            public void run() {//在子线程中访问网络,并缓存图片资源
                                try {
                                    //申明访问的路径
                                    URL url = new URL(path);
                                    //通过路径,得到链接
                                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                                    //设置链接方式
                                    connection.setRequestMethod("GET");
                                    //设置链接超时时间
                                    connection.setConnectTimeout(5000);
                                    //设置写入超时时间
                                    connection.setReadTimeout(5000);
                                    //获取请求响应码
                                    int code = connection.getResponseCode();
                                    if (200 == code) {
                                        //获取请求返回的字节流
                                        InputStream inputStream = connection.getInputStream();
                                        File file = new File(MainActivity.this.getCacheDir(), Base64.encodeToString(path.getBytes(), Base64.DEFAULT));
                                        byte[] buffer = new byte[1024];
                                        int len = 0;
                                        FileOutputStream fos = new FileOutputStream(file);
                                        while ((len = inputStream.read(buffer)) > 0) {
                                            fos.write(buffer, 0, len);
                                        }
                                        fos.close();
                                        inputStream.close();

                                        Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());

                                        //Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                                        //iv_main_showimage.setImageBitmap(bitmap);
                                        Message message = Message.obtain();
                                        message.what = UPDATE;
                                        message.obj = bitmap;
                                        mHandler.sendMessage(message);
                                    } else {
                                        Toast.makeText(MainActivity.this, "reqeust is fail", Toast.LENGTH_SHORT).show();
                                    }
                                } catch (MalformedURLException e) {
                                    e.printStackTrace();
                                } catch (IOException e) {


                                }
                            }
                        }.start();
                    }

                }

            }
        });

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值