C#图片批量下载Demo

news2024/9/26 5:12:01

目录

效果

项目

代码

下载


效果

C#图片批量下载

项目

代码

using Aspose.Cells;
using NLog;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DownloadDemo
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
            NLog.Windows.Forms.RichTextBoxTarget.ReInitializeAllTextboxes(this);
        }

        String startupPath;
        private string excelFileFilter = "表格|*.xlsx;*.xls;";
        private Logger log = NLog.LogManager.GetCurrentClassLogger();
        CancellationTokenSource cts;
        List<ImgInfo> ltImgInfo = new List<ImgInfo>();

        bool saveImg = false;

        private void frmMain_Load(object sender, EventArgs e)
        {
            startupPath = System.Windows.Forms.Application.StartupPath;

            ServicePointManager.Expect100Continue = false;
            ServicePointManager.DefaultConnectionLimit = 512;
        }

        /// <summary>
        /// 选择表格
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Filter = excelFileFilter;
                if (ofd.ShowDialog() != DialogResult.OK) return;
                string excelPath = ofd.FileName;

                Workbook workbook = new Workbook(excelPath);
                Cells cells = workbook.Worksheets[0].Cells;
                System.Data.DataTable dataTable1 = cells.ExportDataTable(1, 0, cells.MaxDataRow, cells.MaxColumn + 1);//noneTitle

                //遍历
                ltImgInfo.Clear();
                ImgInfo temp;
                int imgCount = 0;
                foreach (DataRow row in dataTable1.Rows)
                {
                    temp = new ImgInfo();
                    temp.id = row[0].ToString();
                    temp.title = row[1].ToString();

                    List<string> list = new List<string>();
                    for (int i = 2; i < cells.MaxColumn + 1; i++)
                    {
                        string tempStr = row[i].ToString();
                        if (!string.IsNullOrEmpty(tempStr))
                        {
                            list.Add(tempStr);
                        }
                    }
                    temp.images = list;
                    imgCount = imgCount + list.Count();
                    ltImgInfo.Add(temp);
                }
                log.Info("解析完毕,一共[" + ltImgInfo.Count + "]条记录,[" + imgCount + "]张图片!");
            }
            catch (Exception ex)
            {
                log.Error("解析表格异常:" + ex.Message);
                MessageBox.Show("解析表格异常:" + ex.Message);
            }
        }

        void ShowCostTime(string total, string ocrNum, long time)
        {
            txtTotal.Invoke(new Action(() =>
            {
                TimeSpan ts = TimeSpan.FromMilliseconds(time);
                txtTotal.Text = string.Format("完成:{0}/{1},用时:{2}"
                    , ocrNum
                    , total
                    , ts.ToString()
                    );
            }));
        }

        /// <summary>
        /// 下载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            if (ltImgInfo.Count == 0)
            {
                MessageBox.Show("请先选择表格!");
                return;
            }

            if (!Directory.Exists("img"))
            {
                Directory.CreateDirectory("img");
            }

            if (!Directory.Exists("result"))
            {
                Directory.CreateDirectory("result");
            }

            btnStop.Enabled = true;
            chkSaveImg.Enabled = false;

            if (chkSaveImg.Checked)
            {
                saveImg = true;
            }
            else
            {
                saveImg = false;
            }

            Application.DoEvents();

            cts = new CancellationTokenSource();
            Task.Factory.StartNew(() =>
            {

                int totalCount = ltImgInfo.Count();
                Stopwatch total = new Stopwatch();
                total.Start();  //开始计时
                for (int i = 0; i < ltImgInfo.Count(); i++)
                {

                    //判断是否被取消;
                    if (cts.Token.IsCancellationRequested)
                    {
                        return;
                    }

                    Stopwatch perID = new Stopwatch();
                    perID.Start();//开始计时
                    int imagesCount = ltImgInfo[i].images.Count();
                    for (int j = 0; j < imagesCount; j++)
                    {
                        try
                        {
                            Stopwatch sw = new Stopwatch();
                            sw.Start();  //开始计时
                            HttpWebRequest request = WebRequest.Create(ltImgInfo[i].images[j]) as HttpWebRequest;
                            request.KeepAlive = false;
                            request.ServicePoint.Expect100Continue = false;
                            request.Timeout = 1000;// 1秒
                            request.ReadWriteTimeout = 1000;//1秒

                            request.ServicePoint.UseNagleAlgorithm = false;
                            request.ServicePoint.ConnectionLimit = 65500;
                            request.AllowWriteStreamBuffering = false;
                            request.Proxy = null;

                            request.CookieContainer = new CookieContainer();
                            request.CookieContainer.Add(new Cookie("AspxAutoDetectCookieSupport", "1") { Domain = new Uri(ltImgInfo[i].images[j]).Host });

                            HttpWebResponse wresp = (HttpWebResponse)request.GetResponse();
                            Stream s = wresp.GetResponseStream();
                            Bitmap bmp = (Bitmap)System.Drawing.Image.FromStream(s);
                            s.Dispose();
                            wresp.Close();
                            wresp.Dispose();
                            request.Abort();

                            sw.Stop();
                            log.Info("  " + j + "-->下载用时:" + sw.ElapsedMilliseconds + "毫秒");
                            sw.Restart();

                            if (saveImg)
                            {
                                bmp.Save("img//" + i + "_" + j + ".jpg");
                            }

                        }
                        catch (Exception ex)
                        {
                            log.Error(i + "/" + totalCount + "---->id:" + ltImgInfo[i].id + ",url[" + ltImgInfo[i].images[j] + "],异常:" + ex.Message);
                        }
                    }
                    perID.Stop();
                    log.Info(i + "/" + totalCount + "---->id:" + ltImgInfo[i].id + ",图片张数[" + imagesCount + "],小计用时:" + perID.ElapsedMilliseconds + "毫秒");

                    ShowCostTime(totalCount.ToString(), i.ToString(), total.ElapsedMilliseconds);
                }
                total.Stop();
                log.Info("全部[" + totalCount + "]共计用时:" + total.ElapsedMilliseconds + "毫秒");
            }, TaskCreationOptions.LongRunning);
        }

        /// <summary>
        /// 停止
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            cts.Cancel();
            btnStop.Enabled = false;
            btnStart.Enabled = true;

            chkSaveImg.Enabled = true;
        }
    }
}

using Aspose.Cells;
using NLog;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DownloadDemo
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
            NLog.Windows.Forms.RichTextBoxTarget.ReInitializeAllTextboxes(this);
        }

        String startupPath;
        private string excelFileFilter = "表格|*.xlsx;*.xls;";
        private Logger log = NLog.LogManager.GetCurrentClassLogger();
        CancellationTokenSource cts;
        List<ImgInfo> ltImgInfo = new List<ImgInfo>();

        bool saveImg = false;

        private void frmMain_Load(object sender, EventArgs e)
        {
            startupPath = System.Windows.Forms.Application.StartupPath;

            ServicePointManager.Expect100Continue = false;
            ServicePointManager.DefaultConnectionLimit = 512;
        }

        /// <summary>
        /// 选择表格
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Filter = excelFileFilter;
                if (ofd.ShowDialog() != DialogResult.OK) return;
                string excelPath = ofd.FileName;

                Workbook workbook = new Workbook(excelPath);
                Cells cells = workbook.Worksheets[0].Cells;
                System.Data.DataTable dataTable1 = cells.ExportDataTable(1, 0, cells.MaxDataRow, cells.MaxColumn + 1);//noneTitle

                //遍历
                ltImgInfo.Clear();
                ImgInfo temp;
                int imgCount = 0;
                foreach (DataRow row in dataTable1.Rows)
                {
                    temp = new ImgInfo();
                    temp.id = row[0].ToString();
                    temp.title = row[1].ToString();

                    List<string> list = new List<string>();
                    for (int i = 2; i < cells.MaxColumn + 1; i++)
                    {
                        string tempStr = row[i].ToString();
                        if (!string.IsNullOrEmpty(tempStr))
                        {
                            list.Add(tempStr);
                        }
                    }
                    temp.images = list;
                    imgCount = imgCount + list.Count();
                    ltImgInfo.Add(temp);
                }
                log.Info("解析完毕,一共[" + ltImgInfo.Count + "]条记录,[" + imgCount + "]张图片!");
            }
            catch (Exception ex)
            {
                log.Error("解析表格异常:" + ex.Message);
                MessageBox.Show("解析表格异常:" + ex.Message);
            }
        }

        void ShowCostTime(string total, string ocrNum, long time)
        {
            txtTotal.Invoke(new Action(() =>
            {
                TimeSpan ts = TimeSpan.FromMilliseconds(time);
                txtTotal.Text = string.Format("完成:{0}/{1},用时:{2}"
                    , ocrNum
                    , total
                    , ts.ToString()
                    );
            }));
        }

        /// <summary>
        /// 下载识别
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            if (ltImgInfo.Count == 0)
            {
                MessageBox.Show("请先选择表格!");
                return;
            }

            if (!Directory.Exists("img"))
            {
                Directory.CreateDirectory("img");
            }

            if (!Directory.Exists("result"))
            {
                Directory.CreateDirectory("result");
            }

            btnStop.Enabled = true;
            chkSaveImg.Enabled = false;

            if (chkSaveImg.Checked)
            {
                saveImg = true;
            }
            else
            {
                saveImg = false;
            }

            Application.DoEvents();

            cts = new CancellationTokenSource();
            Task.Factory.StartNew(() =>
            {

                int totalCount = ltImgInfo.Count();
                Stopwatch total = new Stopwatch();
                total.Start();  //开始计时
                for (int i = 0; i < ltImgInfo.Count(); i++)
                {

                    //判断是否被取消;
                    if (cts.Token.IsCancellationRequested)
                    {
                        return;
                    }

                    Stopwatch perID = new Stopwatch();
                    perID.Start();//开始计时
                    int imagesCount = ltImgInfo[i].images.Count();
                    for (int j = 0; j < imagesCount; j++)
                    {
                        try
                        {
                            Stopwatch sw = new Stopwatch();
                            sw.Start();  //开始计时
                            HttpWebRequest request = WebRequest.Create(ltImgInfo[i].images[j]) as HttpWebRequest;
                            request.KeepAlive = false;
                            request.ServicePoint.Expect100Continue = false;
                            request.Timeout = 1000;// 1秒
                            request.ReadWriteTimeout = 1000;//1秒

                            request.ServicePoint.UseNagleAlgorithm = false;
                            request.ServicePoint.ConnectionLimit = 65500;
                            request.AllowWriteStreamBuffering = false;
                            request.Proxy = null;

                            request.CookieContainer = new CookieContainer();
                            request.CookieContainer.Add(new Cookie("AspxAutoDetectCookieSupport", "1") { Domain = new Uri(ltImgInfo[i].images[j]).Host });

                            HttpWebResponse wresp = (HttpWebResponse)request.GetResponse();
                            Stream s = wresp.GetResponseStream();
                            Bitmap bmp = (Bitmap)System.Drawing.Image.FromStream(s);
                            s.Dispose();
                            wresp.Close();
                            wresp.Dispose();
                            request.Abort();

                            sw.Stop();
                            log.Info("  " + j + "-->下载用时:" + sw.ElapsedMilliseconds + "毫秒");
                            sw.Restart();

                            if (saveImg)
                            {
                                bmp.Save("img//" + i + "_" + j + ".jpg");
                            }

                        }
                        catch (Exception ex)
                        {
                            log.Error(i + "/" + totalCount + "---->id:" + ltImgInfo[i].id + ",url[" + ltImgInfo[i].images[j] + "],异常:" + ex.Message);
                        }
                    }
                    perID.Stop();
                    log.Info(i + "/" + totalCount + "---->id:" + ltImgInfo[i].id + ",图片张数[" + imagesCount + "],小计用时:" + perID.ElapsedMilliseconds + "毫秒");

                    ShowCostTime(totalCount.ToString(), i.ToString(), total.ElapsedMilliseconds);
                }
                total.Stop();
                log.Info("全部[" + totalCount + "]共计用时:" + total.ElapsedMilliseconds + "毫秒");
            }, TaskCreationOptions.LongRunning);
        }

        /// <summary>
        /// 停止
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            cts.Cancel();
            btnStop.Enabled = false;
            btnStart.Enabled = true;

            chkSaveImg.Enabled = true;
        }
    }
}

下载

源码下载

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1981221.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【zookeeper 第六篇章】分布式锁

一、分布式锁 分布式锁是控制分布式系统之间同步访问共享资源的一种方式。 二、zookeeper 分布式锁 1、客户端A创建临时顺序节点 demo。并在节点下创建 x_00000001。 2、客户端A判断是否自己是第一个节点&#xff0c;如果是就锁成功。 3、客户端B创建临时顺序节点 demo。 并…

文件操作及面试题

目录 文本文件和二进制文件 File概述 递归去查看某个目录下的所有文件与目录 InputStream概述 OutputStream 概述 文件操作的应用 面试题&#xff1a;递归文件路径并且删除指定文件 将一个指定路径的文件复制到另一个文件中去 1.文件 此处的文件有多种含义&#xff0c…

基于京东家电数据分析与价格预测研究【爬虫、Pyecharts、Flask、机器学习】《商品可换》

文章目录 有需要本项目的代码或文档以及全部资源&#xff0c;或者部署调试可以私信博主项目介绍研究背景研究目的研究意义数据获取数据预处理数据分析与可视化大屏可视化基于Flask的系统框架集成价格预测模型每文一语 有需要本项目的代码或文档以及全部资源&#xff0c;或者部署…

去字节面试大模型算法岗,体验极佳!!

最近这一两周看到不少互联网公司都已经开始秋招提前批了。 不同以往的是&#xff0c;当前职场环境已不再是那个双向奔赴时代了。求职者在变多&#xff0c;HC 在变少&#xff0c;岗位要求还更高了。 最近&#xff0c;我们又陆续整理了很多大厂的面试题&#xff0c;帮助一些球友…

拳击与格斗杂志拳击与格斗杂志社拳击与格斗编辑部2024年第4期目录

搏击研究 拳击运动员灵敏素质训练策略研究 巫金君; 4-6 拳击运动员体能训练的方法与策略 彭天泽;任安萍;高刚; 7-9 高校武术教学与体能训练的结合研究 黄昊; 10-12《拳击与格斗》投稿&#xff1a;cn7kantougao163.com 拳击运动员核心力量训练研究 宋林董;张钰涵…

漏洞挖掘之再探某园区系统

漏洞挖掘之再探某园区系统 上次提到还有一处可能存在任意用户登录的点&#xff0c;最近没什么研究就写一下&#xff0c;顺便看看还有其他漏洞不 0x01 任意用户登录 1、漏洞分析 通过上次提到的搜索new UserBean()的思路&#xff0c;发现还有一处创建用户的方法 public voi…

FPGA设计之跨时钟域(CDC)设计篇(4)----多bit信号的跨时钟域(CDC)处理方法(手撕代码)

1、为什么多bit信号跨时钟域与单bit不同 ? 跨时钟域的处理可以分为两个大类:单Bit信号跨时钟域处理、多Bit信号跨时钟域处理。分类的原因是多bit信号的传递不光只有亚稳态这一个问题,还可能会因为多个信号之间由于工艺、PCB布局等因素导致的信号传输延时(skew)的存在,从而…

【机器学习第8章——集成学习】

机器学习第8章——集成学习 8.集成学习8.1个体与集成弱分类器之间的关系组合时&#xff0c;如何选择学习器怎么组合弱分类器boosting和Bagging 8.2 BoostingAdaBoost算法步骤训练过程 8.3 Bagging与随机森林随机采样(bootstrap)弱学习器结合策略方差与偏差算法流程随机森林 8.4…

2024华硕迷你主机选购指南:全系列覆盖

在选择迷你主机时&#xff0c;消费者往往面临多种选择&#xff0c;而华硕作为知名的电脑硬件制造商&#xff0c;提供了多款性能各异的迷你主机以满足不同用户的需求。在面对华硕迷你主机的选择时&#xff0c;不同的需求和偏好将带领我们走向不同的选择。对于游戏爱好者&#xf…

谈谈我用BaaS开发应用的一年感受

作为一个独立开发者&#xff0c;我一直在寻找高效、便捷的开发工具&#xff0c;直到遇见了MemFire Cloud。今天&#xff0c;我想和大家分享一下我用这款BaaS&#xff08;Backend as a Service&#xff09;开发应用一年的感受。 初识MemFire Cloud 最初接触MemFire Cloud&#…

大模型正在重蹈AI的覆辙?

[ 科技圈这两年什么概念和技术最火&#xff1f;——大模型。 当大模型刚出现的时候&#xff0c;可能谁都不会想到&#xff0c;有一天会如此爆火。 据不完全统计&#xff0c;2020年至2023年间&#xff0c;中国已经发布的参数在10亿规模以上的大模型&#xff0c;就超过80个。 …

8.3 修改mysqld_exporter源码 ,改造成类似blackbox的探针型,实现一对多探测

本节重点介绍 : 官方的mysqld_exporter问题 只能一对一不能像探针一样采集多个实例dsn需要配置环境变量或者配置文件解析 需求说明 改造成类似blackbox的探针型&#xff0c;实现一对多探测改造方案 修改源码prometheus配置文件传参和实例地址获取改造grafana大盘配置成可以切换…

【实用指南】如何选择最适合您的圆形连接器?

圆形连接器是一种电子连接器&#xff0c;其基本结构为圆柱形并且拥有圆形的配合面&#xff0c;这种设计使得它们在物理上区别于矩形或其他形状的连接器。它们通常用于设备之间的互连&#xff0c;属于互连分类中的第5类。 圆形连接器的主要组成部分包括&#xff1a; 插头&#…

引用率全球Top2%大佬耗时几年编写深度学习神书分享!!

介绍 这本深度学习书籍是由一位拥有多重职称和荣誉的顶尖科学家所打造&#xff0c;被评为全球引用率最高的2%科学家之一。这本书被认为是目前最全面系统的深度学习著作&#xff0c;涵盖了深度学习的主流算法模型&#xff0c;对于研究生和博士生具有极高的参考价值。这份完整版…

FPGA的工作本科可以做吗?

在FPGA行业中&#xff0c;这样的偏见一直存在。 很多人认为&#xff0c;只有985、211的硕士才有资格涉足这一领域&#xff0c;甚至有人表示&#xff0c;即使是9、2本硕也难以找到工作&#xff0c;本科生就不要想了。 难到真的只有985&#xff0c;211的研究生才能有机会入行FPG…

人工智能深度学习系列—GANs的对抗博弈:深入解析Adversarial Loss

文章目录 1. 背景介绍2. Adversarial Loss计算公式3. 使用场景4. 代码样例5. 总结 1. 背景介绍 生成对抗网络&#xff08;GANs&#xff09;作为深度学习中的一大突破&#xff0c;其核心机制是通过对抗性训练生成逼真的数据。Adversarial Loss&#xff0c;即对抗性损失&#xf…

网站安全证书的作用和申请方法

网站安全证书的作用 网站安全证书&#xff0c;也被称为SSL证书、HTTPS证书或服务器证书&#xff0c;是一个由受信任的数字证书颁发机构&#xff08;CA&#xff09;审核颁发的数字文件。它的主要作用体现在以下几个方面&#xff1a; 增强用户信任&#xff1a;未使用HTTPS协议的…

幸福人生之理性决策

人人每天都在做决策&#xff0c;小到穿衣吃饭&#xff0c;大到恋爱工作&#xff0c;决策的正确性决定了人生的幸福指数。虽然有些小决策&#xff0c;依靠经验和感性已经足以达到一个满意的结果&#xff1b;有些决策即使错了&#xff0c;对漫长的人生来说也没有太多的影响。 但追…

win10自带dll修复丢失的几种方法,快速修复错误dll文件的方式

DLL文件&#xff0c;即动态链接库文件&#xff0c;是Windows操作系统中不可或缺的组成部分&#xff0c;它们包含了可由多个程序共享的代码和数据。当这些文件损坏或丢失时&#xff0c;可能会导致程序无法正常运行&#xff0c;甚至系统崩溃。 幸运的是&#xff0c;Windows 10操作…

JeecgBoot 低代码平台快速集成 Spring AI

JeecgBoot 是一款基于代码生成器的低代码开发平台&#xff01;前后端分离架构 SpringBoot2.x和3.x&#xff0c;SpringCloud&#xff0c;Ant Design Vue3&#xff0c;Mybatis-plus&#xff0c;Shiro&#xff0c;JWT&#xff0c;支持微服务。强大的代码生成器让前后端代码一键生成…