当前位置: 首页 > 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;}}
}

下载

源码下载

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 在 CMakeLists.txt 中,我需要设置哪些参数来确保我的程序能够正确地链接到 ARM 架构的库?
  • RPP:多智能体强化学习 + 长期个性化推荐
  • AI Edge Torch - PyTorch 模型转换为 TensorFlow Lite 模型 (.tflite)
  • 让一切发生皆有利于我,在人生的长河中,我们常常面临诸多的不确定性和变化
  • AI模型常见的压缩技术分类
  • Prometheus+Grafana保姆笔记(1)——Prometheus+Grafana的安装
  • 【STM32系统】基于STM32设计的按键PWM控制舵机窗帘柜子门禁家居等控制系统——文末资料下载
  • docker上传镜像至阿里云
  • PHP Web服务全攻略:构建与消费的精粹指南
  • easyExcel2.1.6自动trim()的问题
  • 嵌入式八股-面试30题(20240812)
  • RocketMQ 是什么?它的架构是怎样的?和 Kafka 有什么区别?
  • 从分散到集中:TSINGSEE青犀EasyCVR视频汇聚网关在视频整体监控解决方案中的整合作用
  • 抖店飞鸽客服自动回复软件开发教程与下载体验(.NET版)
  • KCTF 闯关游戏:1 ~ 7 关
  • [js高手之路]搞清楚面向对象,必须要理解对象在创建过程中的内存表示
  • 《Java编程思想》读书笔记-对象导论
  • 【402天】跃迁之路——程序员高效学习方法论探索系列(实验阶段159-2018.03.14)...
  • 11111111
  • 30秒的PHP代码片段(1)数组 - Array
  • android 一些 utils
  • Android路由框架AnnoRouter:使用Java接口来定义路由跳转
  • C++类的相互关联
  • conda常用的命令
  • cookie和session
  • nodejs:开发并发布一个nodejs包
  • 安装python包到指定虚拟环境
  • 诡异!React stopPropagation失灵
  • 聊聊directory traversal attack
  • 吴恩达Deep Learning课程练习题参考答案——R语言版
  • 移动端 h5开发相关内容总结(三)
  • 责任链模式的两种实现
  • 通过调用文摘列表API获取文摘
  • ​人工智能之父图灵诞辰纪念日,一起来看最受读者欢迎的AI技术好书
  • #Linux(Source Insight安装及工程建立)
  • #QT(TCP网络编程-服务端)
  • #我与Java虚拟机的故事#连载12:一本书带我深入Java领域
  • (1)(1.9) MSP (version 4.2)
  • (6)设计一个TimeMap
  • (BFS)hdoj2377-Bus Pass
  • (env: Windows,mp,1.06.2308310; lib: 3.2.4) uniapp微信小程序
  • (TipsTricks)用客户端模板精简JavaScript代码
  • (利用IDEA+Maven)定制属于自己的jar包
  • (一)springboot2.7.6集成activit5.23.0之集成引擎
  • (转)Android学习笔记 --- android任务栈和启动模式
  • (转)C#调用WebService 基础
  • (转)ORM
  • (转)重识new
  • .gitattributes 文件
  • .net core 实现redis分片_基于 Redis 的分布式任务调度框架 earth-frost
  • .NET Remoting学习笔记(三)信道
  • .net(C#)中String.Format如何使用
  • .NET/C# 检测电脑上安装的 .NET Framework 的版本
  • .NET程序集编辑器/调试器 dnSpy 使用介绍
  • .net经典笔试题