• c# 下载网页图片


    也是比较老的东西了

    最近用到

    记录下以免以后忘了

    要下载图片首先要有图片地址

    要有图片地址就要先把网页下下来分析下URL

    下载网页一般用两种方法

    1,用 system.net.webclient

    using System.Net;
    using System.Windows.Forms;
    
    string url = "http://www.cnblogs.com";
    string result = null;
    
    try
    {
        WebClient client = new WebClient();
        result = client.DownloadString( url );
    }
    catch (Exception ex)
    {
        MessageBox.Show( ex.Message );
    }

    2,用 System.Net.HttpWebRequest

    using System.Net;
    using System.IO;
    using System.Windows.Forms;
    
    string result = null;
    string url = "http://www.cnblogs.com";
    WebResponse response = null;
    StreamReader reader = null;
    
    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create( url );
        request.Method = "GET";
        response = request.GetResponse();
        reader = new StreamReader( response.GetResponseStream(), Encoding.UTF8 );
        result = reader.ReadToEnd();
    }
    catch (Exception ex)
    {
        MessageBox.Show( ex.Message );
    }
    finally
    {
        if (reader != null)
            reader.Close();
        if (response != null)
            response.Close();
    }

    至于怎么找图片url略过,直接说下载图片吧

    其实和上面一样,也有两种方法:

    1,WebRequest和WebResponse

    WebRequest request = WebRequest.Create("http://images.cnblogs.com/logo_small.gif");
    WebResponse response = request.GetResponse();
    Stream reader = response.GetResponseStream();
    FileStream writer = new FileStream("x:\\pic.jpg", FileMode.OpenOrCreate, FileAccess.Write);
    byte[] buff = new byte[512];
    int c = 0; //实际读取的字节数
    while ((c=reader.Read(buff, 0, buff.Length)) > 0)
    {
        writer.Write(buff, 0, c);
    }
    writer.Close();
    writer.Dispose();
    reader.Close();
    reader.Dispose();
    response.Close();

    2,WebClient

    string url = "http://images.cnblogs.com/logo_small.gif";
    string filepath = "x:\\pic.jpg";
    WebClient mywebclient = new WebClient();
    mywebclient.DownloadFile(url, filepath);



    大体就这么多…

    作者:sun8134
             
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    2021-07-12 部分集训题目题解
    2021-07-09/11 部分集训题目题解
    k8s删除Terminating状态的命名空间
    yum命令安装jenkins
    Jenkins构建docker镜像
    jenkins获取当前构建任务的构建人
    Kubernetes kubeconfig配置文件
    K8S中使用gfs当存储
    人类视觉系统对颜色和亮度的感知
    荧光的应用之全内反射荧光显微镜(TIRFM)
  • 原文地址:https://www.cnblogs.com/sun8134/p/1771187.html
Copyright © 2020-2023  润新知