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

【大模型RAG】拍照搜题技术架构速览:三层管道、两级检索、兜底大模型

摘要 拍照搜题系统采用“三层管道&#xff08;多模态 OCR → 语义检索 → 答案渲染&#xff09;、两级检索&#xff08;倒排 BM25 向量 HNSW&#xff09;并以大语言模型兜底”的整体框架&#xff1a; 多模态 OCR 层 将题目图片经过超分、去噪、倾斜校正后&#xff0c;分别用…...

(十)学生端搭建

本次旨在将之前的已完成的部分功能进行拼装到学生端&#xff0c;同时完善学生端的构建。本次工作主要包括&#xff1a; 1.学生端整体界面布局 2.模拟考场与部分个人画像流程的串联 3.整体学生端逻辑 一、学生端 在主界面可以选择自己的用户角色 选择学生则进入学生登录界面…...

.Net框架,除了EF还有很多很多......

文章目录 1. 引言2. Dapper2.1 概述与设计原理2.2 核心功能与代码示例基本查询多映射查询存储过程调用 2.3 性能优化原理2.4 适用场景 3. NHibernate3.1 概述与架构设计3.2 映射配置示例Fluent映射XML映射 3.3 查询示例HQL查询Criteria APILINQ提供程序 3.4 高级特性3.5 适用场…...

使用分级同态加密防御梯度泄漏

抽象 联邦学习 &#xff08;FL&#xff09; 支持跨分布式客户端进行协作模型训练&#xff0c;而无需共享原始数据&#xff0c;这使其成为在互联和自动驾驶汽车 &#xff08;CAV&#xff09; 等领域保护隐私的机器学习的一种很有前途的方法。然而&#xff0c;最近的研究表明&…...

django filter 统计数量 按属性去重

在Django中&#xff0c;如果你想要根据某个属性对查询集进行去重并统计数量&#xff0c;你可以使用values()方法配合annotate()方法来实现。这里有两种常见的方法来完成这个需求&#xff1a; 方法1&#xff1a;使用annotate()和Count 假设你有一个模型Item&#xff0c;并且你想…...

如何在看板中有效管理突发紧急任务

在看板中有效管理突发紧急任务需要&#xff1a;设立专门的紧急任务通道、重新调整任务优先级、保持适度的WIP&#xff08;Work-in-Progress&#xff09;弹性、优化任务处理流程、提高团队应对突发情况的敏捷性。其中&#xff0c;设立专门的紧急任务通道尤为重要&#xff0c;这能…...

Spring AI 入门:Java 开发者的生成式 AI 实践之路

一、Spring AI 简介 在人工智能技术快速迭代的今天&#xff0c;Spring AI 作为 Spring 生态系统的新生力量&#xff0c;正在成为 Java 开发者拥抱生成式 AI 的最佳选择。该框架通过模块化设计实现了与主流 AI 服务&#xff08;如 OpenAI、Anthropic&#xff09;的无缝对接&…...

【C语言练习】080. 使用C语言实现简单的数据库操作

080. 使用C语言实现简单的数据库操作 080. 使用C语言实现简单的数据库操作使用原生APIODBC接口第三方库ORM框架文件模拟1. 安装SQLite2. 示例代码:使用SQLite创建数据库、表和插入数据3. 编译和运行4. 示例运行输出:5. 注意事项6. 总结080. 使用C语言实现简单的数据库操作 在…...

AI书签管理工具开发全记录(十九):嵌入资源处理

1.前言 &#x1f4dd; 在上一篇文章中&#xff0c;我们完成了书签的导入导出功能。本篇文章我们研究如何处理嵌入资源&#xff0c;方便后续将资源打包到一个可执行文件中。 2.embed介绍 &#x1f3af; Go 1.16 引入了革命性的 embed 包&#xff0c;彻底改变了静态资源管理的…...

现有的 Redis 分布式锁库(如 Redisson)提供了哪些便利?

现有的 Redis 分布式锁库&#xff08;如 Redisson&#xff09;相比于开发者自己基于 Redis 命令&#xff08;如 SETNX, EXPIRE, DEL&#xff09;手动实现分布式锁&#xff0c;提供了巨大的便利性和健壮性。主要体现在以下几个方面&#xff1a; 原子性保证 (Atomicity)&#xff…...