通过网络链接显示网页中的图片

本文介绍了一种方法,通过网络链接获取HTML文档,解析img标签的src属性,然后在Android应用中使用ImageView显示这些网络图片。代码示例中,存在一些问题,比如只适用于特定网页,网络操作应在子线程执行等。

想法:通过网络链接,获取html文档,再从文档中得到img标签,处理得到src,再通过imageview进行显示

代码会有一点问题,仅作参考:

1.ConnectDeal 类,代码实现了以上全部功能:

URL使用了baidu,因为网页的html会有所不同,所以其他网页可能会报错(虽然使用了正则表达式Matcher,但确实其他网页有报错);还有网络操作必须在子进程中完成。

public class ConnectDeal {
    private final static String URL="http://www.baidu.com";
    
    TextView textView2 = null;
    ImageView imageView=null;
    //网页的HTML文档
    private static String HTML = "";
    // 获取img标签正则
    private static final String IMGURL_REG = "<img.*src\\s*=\\s*(.*?)[^>]*?>";  // 获取src路径则
    private static final String IMGSRC_REG = "src\\s*=\\s*\"?(.*?)(\"|>|\\s+)";
    
    public ConnectDeal(TextView textView,ImageView imageView) {
        // TODO Auto-generated constructor stub
        this.imageView = imageView;
        this.textView2 = textView;
//        getHtml();
    }
    

    public void getHtml() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
            try {
                //获取html
                String html =getPictureData(URL);
                
                //获取img标签
                List<String> list =getImageURL(html);
     
                //获取img src
                list = getImageSrc(list);
                textView2.setText(list.toString());
                
                //将图片显示再imageview
                lookImg(list);
            } catch (Exception e) {
                Log.e("GetHtmlCodeActivity", e.toString());
                
            }
            }
        }).start();
    }
    
      //得到Html文档,函数名有问题
    public String getPictureData(String path) throws Exception{
        // 类 URL 代表一个统一资源定位符,它是指向互联网“资源”的指针。
        URL url = new URL(path);
        // 每个 HttpURLConnection 实例都可用于生成单个请求,
        //但是其他实例可以透明地共享连接到 HTTP 服务器的基础网络
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置 URL 请求的方法
        conn.setRequestMethod("GET");
        //设置一个指定的超时值(以毫秒为单位),
        //该值将在打开到此 URLConnection 引用的资源的通信链接时使用。
        conn.setConnectTimeout(5 * 1000);
        // conn.getInputStream()返回从此打开的连接读取的输入流
        InputStream inStream = conn.getInputStream();// 通过输入流获取html数据
        byte[] data = readInputStream(inStream);// 得到html的二进制数据
        String html = new String(data);
        return html;
        
    }
    //读取输入流中的数据,返回字节数组byte[]
    public byte[] readInputStream(InputStream inStream) throws Exception{
        //此类实现了一个输出流,其中的数据被写入一个 byte 数组
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        // 字节数组
        byte[] buffer = new byte[1024];
        int len = 0;
        //从输入流中读取一定数量的字节,并将其存储在缓冲区数组buffer 中
        while ((len = inStream.read(buffer)) != -1) {
            // 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此输出流
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        //toByteArray()创建一个新分配的 byte 数组。
        return outStream.toByteArray();
    }
        

    
    //获取img标签
    public List<String> getImageURL(String html) {
        Matcher matcher = Pattern.compile(IMGURL_REG).matcher(html);
        List<String> list = new ArrayList<String>();
        Log.e("my", "finding");
        while (matcher.find()) {
            list.add(matcher.group());
        }
        Log.e("my", "list : 12"+list.toString());
        return list;
    }

//获取img中src链接;
    public static List<String> getImageSrc(List<String> listUrl) {
        List<String> listSrc = new ArrayList<String>();
        for (String img : listUrl) {
            Matcher matcher = Pattern.compile(IMGSRC_REG).matcher(img);
            while (matcher.find()){

                listSrc.add(matcher.group().substring(6,
                        matcher.group().length() - 1));
            }

        }
        System.out.println(listSrc.toString());
        return listSrc;
    }

//图片放入imageView

    private void lookImg(List<String> list) throws IOException {
        URL uri = null;
        Bitmap bitmap =null;
        for(String url : list) {
            url ="http://"+url;
            uri =new URL(url);
            HttpURLConnection connection =(HttpURLConnection) uri.openConnection();
            connection.connect();
            InputStream is=connection.getInputStream();
            bitmap =BitmapFactory.decodeStream(is);
            is.close();
            imageView.setImageBitmap(bitmap);
        }
        //只看了最后一张
        
    }
    

}

2.MainActivity中

使用了两个控件textview 和 imageview

直接实现类,调用getHtml()函数

ConnectDeal connectDeal =new ConnectDeal(textView2, imageView);
connectDeal.getHtml();

3.Manifest 加入网络权限

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

最后的效果

textview显示img的src表示查找到的图片

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值