当前位置: 首页 > news >正文

C#图片批量下载Demo

目录

效果

项目

代码

下载


效果

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;}}
}

下载

源码下载

相关文章:

C#图片批量下载Demo

目录 效果 项目 代码 下载 效果 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.…...

部署Springboot + Vue 项目到远程服务器Windows10系统的详细配置

远程服务器操作系统为Windows系统&#xff0c;Java程序环境&#xff0c;Maven环境都安装有&#xff0c;Mysql ,Redis等都有的前提下 1. mysql数据库导入&#xff0c;非常简单很好操作&#xff0c;这里省略。。比如用HeidiSql 或者Navicat 工具导入数据库 2. 后端javaSpringb…...

智驭灌区,科技领航—— 高效灌区信息化系统管理平台

在水资源日益珍贵的今天&#xff0c;传统灌区的粗放式管理模式已难以满足现代农业的发展需求。我们自豪地推出——灌区信息化系统管理平台&#xff0c;以科技赋能水利&#xff0c;引领灌溉管理进入智能化、精细化新时代。 【智能决策&#xff0c;精准灌溉】 告别传统灌溉的盲目…...

下载免费设计素材,有这7个网站就够了

7个免费设计素材网站&#xff0c;这些网站提供了大量的免费资源&#xff0c;包括图片、字体、图标、模板等&#xff0c;涵盖了多种风格和主题&#xff0c;能够满足不同设计师和创作者的需求。无论是用于个人项目还是商业用途&#xff0c;这些网站都能给你提供丰富的选择&#x…...

【漏洞复现】某赛通数据泄露防护(DLP)系统 NetSecConfigAjax SQL注入漏洞

0x01 产品简介 某赛通新一代数据泄露防护系统&#xff08;简称 DLP&#xff09;&#xff0c;以服务企事业单位进行数据资产梳理、数据安全防护为目标。系统采用平台化管理&#xff0c;将终端DLP、网络DLP、邮件DLP、存储扫描DLP、API 接口DLP 进行统一管理&#xff0c;模块化控…...

c++中的仿函数

目录 什么是仿函数&#xff1f; 仿函数的定义与使用 仿函数与普通函数的比较 实际应用场景 总结 当谈论到 C 编程中的灵活性和效率时&#xff0c;仿函数&#xff08;Functor&#xff09;是一个重要的概念。它不仅可以提供比普通函数更多的功能&#xff0c;还能够在很多情况…...

springboot整合mybatis-plus和pagehelper插件报错,

在springboot和myabtisplus版本没有冲突的情况下&#xff0c;MybatisPlusAutoConfiguration配置类没有生效&#xff0c;查看该类发现存在生效条件&#xff0c;即&#xff1a; 1.必须存在数据源的Bean对象 2.必须存在SqlSessionFactory和SqlSessionFactoryBean类&#xff08;这…...

趋动科技荣登「AIGC赋能金融创新引领者TOP20」

2023年11月28日&#xff0c;“极新AIGC行业峰会”在北京召开&#xff0c;峰会以“AI落地”为指引&#xff0c;探究AI实践与产业化。 从制造业到金融服务业&#xff0c;从医疗保健到交通运输&#xff0c;从文化娱乐到消费零售&#xff0c;智能客服、数字人直播、智能巡检机器人&…...

SOPHGO算能科技BM1684盒子占用空间满的问题解决

目录 1 问题由来 2 问题排查与解决 1 问题由来 安装软件的时候发现&#xff0c;软件根本安装不上了&#xff0c;用df -h看到根目录已经满了 rootbm1684:~# df -h Filesystem Size Used Avail Use% Mounted on overlay 5.8G 5.7G 0 100% / devtmpfs …...

Spring Boot实用小技巧 - - 第523篇

《国内最全的Spring Boot系列之一》 《国内最全的Spring Boot系列之二》 《国内最全的Spring Boot系列之三》 《国内最全的Spring Boot系列之四》 《国内最全的Spring Boot系列之五》 《国内最全的Spring Boot系列之六》 《国内最全的Spring Boot系列之七》 Spring的Sma…...

安卓App开发 篇二:Android UI和布局

文章目录 系列文章Jetpack Compose基本语法可组合函数预览布局元素基于槽位(slot-based)的布局横屏处理实现布局设计布局检查器工具Material Design使用字符串等资源列表和动画LazyColumn 和 LazyRowremember 和 mutableStateOf事件mutableStateOfremember局部更新组件(官方…...

k8s基本介绍

Kubernetes, also known as K8s, is an open source system for automating deployment, scaling, and management of containerized applications. Kubernetes&#xff0c;也称为k8&#xff0c;是一个用于自动化部署、扩展和管理容器化应用程序的开源系统。 使用go语言编写ht…...

go http启动应用程序

udpserver udpserver 是go程序需要启动的程序 #include <iostream> #include <unistd.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <thread>const int BUFFER_SIZE 1024;int udpSocket; struct …...

Redis:概念、部署、配置、优化

目录 关系型数据库与非关系型数据库 关系型数据库 非关系型数据库 非关系型数据库存在的原因 Redis 概念 优点 Redis部署流程 初步设置 安装 初始化 初始化时指定的参数说明 Redis配置文件 修改监听地址 Redis远程连接 远程连接 测试服务端状态 redis-benchm…...

华为OD-D卷找座位

在一个大型体育场内举办了一场大型活动&#xff0c;由于疫情防控的需要&#xff0c;要求每位观众的必须间隔至少一个空位才允许落座。现在给出一排观众座位分布图&#xff0c;座位中存在已落座的观众&#xff0c;请计算出&#xff0c;在不移动现有观众座位的情况下&#xff0c;…...

Go sdk下载和配置环境变量

本文目录 SDK下载环境变量配置测试 SDK下载 下载地址&#xff1a;https://golang.google.cn/dl/ 更多版本&#xff0c;找到1.9.2 我是win10 64位的&#xff0c;我找到这个下载 下载之后解压&#xff0c;可以看到bin文件夹。 环境变量配置 我的电脑 -> 属性 -> 高级…...

qt的项目结构

目录 创建新的项目 第一个hell0程序&#xff0c;qt的项目结构 main函数 Widget头文件: pro文件 命名规范 QtCreator 常用快捷键 Qt里边绝大部分的类都是继承自QObject是一个顶层类 父子关系 Qt坐标系 QT常用API函数 对象树 信号和槽机制 自定义信号和槽 自定义信号…...

【NLP】文本特征处理:n-gram特征和文本长度规范

文章目录 1、本章目标2、n-gram特征2.1、概念2.2、举个例子2.3、代码 3、文本长度规范及其作用4、小结 &#x1f343;作者介绍&#xff1a;双非本科大三网络工程专业在读&#xff0c;阿里云专家博主&#xff0c;专注于Java领域学习&#xff0c;擅长web应用开发、数据结构和算法…...

ESP32人脸识别开发 ---partitions.csv配置的一些说明(五)

配置的文件在这个位置 esp-who/examples/esp32-s3-eye/partitions.csv factory, app, factory, 0x010000, 4000K, model, data, spiffs, , 3900K, &#xff08;这个是语音相关的&#xff09; nvs, data, nvs, , 16K, fr, data, ,…...

【学习笔记】Matlab和python双语言的学习(图论最短路径)

文章目录 前言一、图论基本概念示例 二、代码实现----Matlab三、代码实现----python总结 前言 通过模型算法&#xff0c;熟练对Matlab和python的应用。 学习视频链接&#xff1a; https://www.bilibili.com/video/BV1EK41187QF?p36&vd_source67471d3a1b4f517b7a7964093e6…...

Python爬虫实战:研究MechanicalSoup库相关技术

一、MechanicalSoup 库概述 1.1 库简介 MechanicalSoup 是一个 Python 库,专为自动化交互网站而设计。它结合了 requests 的 HTTP 请求能力和 BeautifulSoup 的 HTML 解析能力,提供了直观的 API,让我们可以像人类用户一样浏览网页、填写表单和提交请求。 1.2 主要功能特点…...

从零实现富文本编辑器#5-编辑器选区模型的状态结构表达

先前我们总结了浏览器选区模型的交互策略&#xff0c;并且实现了基本的选区操作&#xff0c;还调研了自绘选区的实现。那么相对的&#xff0c;我们还需要设计编辑器的选区表达&#xff0c;也可以称为模型选区。编辑器中应用变更时的操作范围&#xff0c;就是以模型选区为基准来…...

java调用dll出现unsatisfiedLinkError以及JNA和JNI的区别

UnsatisfiedLinkError 在对接硬件设备中&#xff0c;我们会遇到使用 java 调用 dll文件 的情况&#xff0c;此时大概率出现UnsatisfiedLinkError链接错误&#xff0c;原因可能有如下几种 类名错误包名错误方法名参数错误使用 JNI 协议调用&#xff0c;结果 dll 未实现 JNI 协…...

STM32F4基本定时器使用和原理详解

STM32F4基本定时器使用和原理详解 前言如何确定定时器挂载在哪条时钟线上配置及使用方法参数配置PrescalerCounter ModeCounter Periodauto-reload preloadTrigger Event Selection 中断配置生成的代码及使用方法初始化代码基本定时器触发DCA或者ADC的代码讲解中断代码定时启动…...

Psychopy音频的使用

Psychopy音频的使用 本文主要解决以下问题&#xff1a; 指定音频引擎与设备&#xff1b;播放音频文件 本文所使用的环境&#xff1a; Python3.10 numpy2.2.6 psychopy2025.1.1 psychtoolbox3.0.19.14 一、音频配置 Psychopy文档链接为Sound - for audio playback — Psy…...

CMake 从 GitHub 下载第三方库并使用

有时我们希望直接使用 GitHub 上的开源库,而不想手动下载、编译和安装。 可以利用 CMake 提供的 FetchContent 模块来实现自动下载、构建和链接第三方库。 FetchContent 命令官方文档✅ 示例代码 我们将以 fmt 这个流行的格式化库为例,演示如何: 使用 FetchContent 从 GitH…...

项目部署到Linux上时遇到的错误(Redis,MySQL,无法正确连接,地址占用问题)

Redis无法正确连接 在运行jar包时出现了这样的错误 查询得知问题核心在于Redis连接失败&#xff0c;具体原因是客户端发送了密码认证请求&#xff0c;但Redis服务器未设置密码 1.为Redis设置密码&#xff08;匹配客户端配置&#xff09; 步骤&#xff1a; 1&#xff09;.修…...

wpf在image控件上快速显示内存图像

wpf在image控件上快速显示内存图像https://www.cnblogs.com/haodafeng/p/10431387.html 如果你在寻找能够快速在image控件刷新大图像&#xff08;比如分辨率3000*3000的图像&#xff09;的办法&#xff0c;尤其是想把内存中的裸数据&#xff08;只有图像的数据&#xff0c;不包…...

在 Spring Boot 中使用 JSP

jsp&#xff1f; 好多年没用了。重新整一下 还费了点时间&#xff0c;记录一下。 项目结构&#xff1a; pom: <?xml version"1.0" encoding"UTF-8"?> <project xmlns"http://maven.apache.org/POM/4.0.0" xmlns:xsi"http://ww…...

离线语音识别方案分析

随着人工智能技术的不断发展&#xff0c;语音识别技术也得到了广泛的应用&#xff0c;从智能家居到车载系统&#xff0c;语音识别正在改变我们与设备的交互方式。尤其是离线语音识别&#xff0c;由于其在没有网络连接的情况下仍然能提供稳定、准确的语音处理能力&#xff0c;广…...