Android读取网络图片到本地的简约的实现

今天在网上看到了一个关于读取网络文件的小视频,觉得不错,拿来与大家分享


思路


具体的思路比较的简单,但是思想非常的单纯。那就是输入一个网址,点击按钮,将从网络上获取的一张图片显示到一个ImageView控件上。
这样看来,我们需要用到的核心就是网络操作了。说白了,就是读取网络流文件了。

代码展示


首先是主界面的布局文件


<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" >

    <EditText 
        android:id="@+id/et_website"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="please type the url "
        />
    <Button 
        android:id="@+id/btn_get"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Check"

        />
    <ImageView 
        android:id="@+id/iv_picture"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher"
        />

</LinearLayout>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

然后是主界面的逻辑代码

package com.example.getphotobyxml;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.service.ImageService;

public class MainActivity extends Activity {

    private EditText mEt_url;
    private ImageView mIv_picture;
    private Button mBtn_get;

    /**
     * 初始化相关的需要使用到的ID
     */
    public void init() {
        mEt_url = (EditText) findViewById(R.id.et_website);
        mIv_picture = (ImageView) findViewById(R.id.iv_picture);
        mBtn_get = (Button) findViewById(R.id.btn_get);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //记得要调用哦
        init();

        mBtn_get.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String website = mEt_url.getText().toString();
                if (website == null || website.equals("")) {
                    Toast.makeText(MainActivity.this, "请输入正确的网址哦!",
                            Toast.LENGTH_LONG).show();
                    return;
                }
                byte[] bytes;

                try {
                    bytes = ImageService.getImage(website);
                    Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,
                            bytes.length);
                    mIv_picture.setImageBitmap(bitmap);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 从网络以XML的方式获得一张图片,并显示到一个ImageView上
     * 按钮事件可以直接不注册onClickListener,而使用这个方法
     * @param view
     */
    public void getPicture(View view) {
        String website = mEt_url.getText().toString();
        if (website == null || website.equals("")) {
            Toast.makeText(this, "请输入正确的网址哦!", Toast.LENGTH_LONG).show();
            return;
        }
        byte[] bytes;

        try {
            bytes = ImageService.getImage(website);
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,
                    bytes.length);
            mIv_picture.setImageBitmap(bitmap);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91

service 以及 tools助手

package com.example.service;

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

import com.example.utils.StreamTool;

/**
*图片服务的业务类
*/
public class ImageService {

    public static byte[] getImage(String website) throws Exception {

        URL url = new URL(website);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        if(conn.getResponseCode()==200){
            InputStream inputStream = conn.getInputStream();
            byte[] bytes = StreamTool.read(inputStream);
            return bytes;
        }
        return "读取网络数据失败".getBytes();
    }



}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

package com.example.utils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

/**
*专门用于将输入流转换成一个字节数组的utils类
*/
public class StreamTool {

    public static byte[] read(InputStream inputStream) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int len = 0;
        while((len = inputStream.read(buf))!=-1){
            baos.write(buf, 0 ,len);
        }
        baos.close();
        return buf;
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

总结


这里面的代码是非常的简单的,我这里贴出代码的主要的目的是为了展示分层的思想,以及重构的艺术。
在代码中我们看到了,创建了专门的类来完成专门的工作。而且不同的层次的类,处理的业务也是不一样的。这样有助于我们以面向对象的方式编程,带来更加清晰的逻辑。

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

猜你喜欢

转载自www.cnblogs.com/djuwcnhwbx/p/10325968.html