当前位置: 首页 > 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…...

UE5 学习系列(三)创建和移动物体

这篇博客是该系列的第三篇&#xff0c;是在之前两篇博客的基础上展开&#xff0c;主要介绍如何在操作界面中创建和拖动物体&#xff0c;这篇博客跟随的视频链接如下&#xff1a; B 站视频&#xff1a;s03-创建和移动物体 如果你不打算开之前的博客并且对UE5 比较熟的话按照以…...

Aspose.PDF 限制绕过方案:Java 字节码技术实战分享(仅供学习)

Aspose.PDF 限制绕过方案&#xff1a;Java 字节码技术实战分享&#xff08;仅供学习&#xff09; 一、Aspose.PDF 简介二、说明&#xff08;⚠️仅供学习与研究使用&#xff09;三、技术流程总览四、准备工作1. 下载 Jar 包2. Maven 项目依赖配置 五、字节码修改实现代码&#…...

Redis:现代应用开发的高效内存数据存储利器

一、Redis的起源与发展 Redis最初由意大利程序员Salvatore Sanfilippo在2009年开发&#xff0c;其初衷是为了满足他自己的一个项目需求&#xff0c;即需要一个高性能的键值存储系统来解决传统数据库在高并发场景下的性能瓶颈。随着项目的开源&#xff0c;Redis凭借其简单易用、…...

解读《网络安全法》最新修订,把握网络安全新趋势

《网络安全法》自2017年施行以来&#xff0c;在维护网络空间安全方面发挥了重要作用。但随着网络环境的日益复杂&#xff0c;网络攻击、数据泄露等事件频发&#xff0c;现行法律已难以完全适应新的风险挑战。 2025年3月28日&#xff0c;国家网信办会同相关部门起草了《网络安全…...

C语言中提供的第三方库之哈希表实现

一. 简介 前面一篇文章简单学习了C语言中第三方库&#xff08;uthash库&#xff09;提供对哈希表的操作&#xff0c;文章如下&#xff1a; C语言中提供的第三方库uthash常用接口-CSDN博客 本文简单学习一下第三方库 uthash库对哈希表的操作。 二. uthash库哈希表操作示例 u…...

苹果AI眼镜:从“工具”到“社交姿态”的范式革命——重新定义AI交互入口的未来机会

在2025年的AI硬件浪潮中,苹果AI眼镜(Apple Glasses)正在引发一场关于“人机交互形态”的深度思考。它并非简单地替代AirPods或Apple Watch,而是开辟了一个全新的、日常可接受的AI入口。其核心价值不在于功能的堆叠,而在于如何通过形态设计打破社交壁垒,成为用户“全天佩戴…...

云原生周刊:k0s 成为 CNCF 沙箱项目

开源项目推荐 HAMi HAMi&#xff08;原名 k8s‑vGPU‑scheduler&#xff09;是一款 CNCF Sandbox 级别的开源 K8s 中间件&#xff0c;通过虚拟化 GPU/NPU 等异构设备并支持内存、计算核心时间片隔离及共享调度&#xff0c;为容器提供统一接口&#xff0c;实现细粒度资源配额…...

从实验室到产业:IndexTTS 在六大核心场景的落地实践

一、内容创作&#xff1a;重构数字内容生产范式 在短视频创作领域&#xff0c;IndexTTS 的语音克隆技术彻底改变了配音流程。B 站 UP 主通过 5 秒参考音频即可克隆出郭老师音色&#xff0c;生成的 “各位吴彦祖们大家好” 语音相似度达 97%&#xff0c;单条视频播放量突破百万…...

Git 命令全流程总结

以下是从初始化到版本控制、查看记录、撤回操作的 Git 命令全流程总结&#xff0c;按操作场景分类整理&#xff1a; 一、初始化与基础操作 操作命令初始化仓库git init添加所有文件到暂存区git add .提交到本地仓库git commit -m "提交描述"首次提交需配置身份git c…...

基于谷歌ADK的 智能产品推荐系统(2): 模块功能详解

在我的上一篇博客&#xff1a;基于谷歌ADK的 智能产品推荐系统(1): 功能简介-CSDN博客 中我们介绍了个性化购物 Agent 项目&#xff0c;该项目展示了一个强大的框架&#xff0c;旨在模拟和实现在线购物环境中的智能导购。它不仅仅是一个简单的聊天机器人&#xff0c;更是一个集…...