C#图片批量下载Demo

embedded/2024/12/21 17:10:27/

目录

效果

项目

代码

下载


效果

项目

代码

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.ppmy.cn/embedded/93411.html

相关文章

深入理解单元测试与JUnit:从基础概念到实践操作

文章目录 前言一、单元测试是什么&#xff1f;单元测试的特点单元测试的好处 二、junit是什么&#xff1f;三、操作步骤1.junit安装2.maven新建项目3. 新建java文件4. 生成测试类5. 编写测试方法6. 测试结果 总结 前言 随着软件开发行业的不断发展&#xff0c;测试的重要性日益…

利用 Vue.js 的计算属性精简和增强你的前端逻辑

目录 格式化显示数据 计算购物车总价 过滤列表 依赖其他计算属性 在开发现代web应用时,Vue.js 作为一个轻量级且功能强大的前端框架,提供了许多便利的特性,其中计算属性(computed properties)是其最富盛名和实用的功能之一。计算属性允许开发者基于组件的数据动态生成…

vue2动态切换组件(demo)

demo背景&#xff1a;页面上新增字段&#xff08;接口返回&#xff09;&#xff0c;根据新增字段的类型来匹配相应的输入框&#xff0c;比如int匹配数字输入框&#xff0c;String匹配字符类型输入框&#xff0c;data匹配时间输入框... 新增字段 <el-form-item label"字…

SQL Server 事务

1. 什么是事务 SQL Server 事务是数据库操作的一个基本特性&#xff0c;它允许你将一系列数据库操作组合成一个原子单元&#xff0c;这个单元中的所有操作要么全部成功&#xff0c;要么全部失败。事务具有以下四个重要的属性&#xff0c;通常被称为ACID属性。 2、事务的特性 原…

nodejs爬虫示例<爬取官网首页>

背景 大家都知道&#xff0c;Python爬虫是最牛掰的&#xff0c;那么前端人员能玩爬虫吗&#xff1f; 会Python&#xff1a;那么爬虫会很舒服&#xff0c;Python有很多成熟的库&#xff0c;我们可以直接拿来用不会Python&#xff1a;爬虫也没那么难&#xff0c;就是需要摸索一…

自动化测试工具:Selenium

Selenium作为一种广泛使用的自动化测试工具&#xff0c;尤其在Web自动化测试领域发挥着重要作用。为了提升测试效率、增强测试的可维护性和可读性&#xff0c;Selenium经常与各种流行框架集成&#xff0c;其中pytest和Allure报告是两个非常受欢迎的选项。本文将详细探讨Seleniu…

HTTPS

重要:面试关于HTTPS的工作流程 关于HTTPS的基本概念 HTTPS HTTP SSL 加密 既然要保证数据安全, 就需要进⾏ "加密". ⽹络传输中不再直接传输明⽂了, ⽽是加密之后的 "密⽂". 加密的⽅式有很多, 但是整体可以分成两⼤类: 对称加密 和 ⾮对称加密 明文…

Adobe Substance 3D Sampler v4.2.2.3719 解锁版下载安装教程(3D材质管理软件)

前言 Substance 3D Sampler简称“Sa”是一款由Adobe新推出的3D真实材质贴图制作软件。允许用户通过调整和混合现有材料&#xff0c;或通过扫描&#xff08;单个或多个图像&#xff09;中提取新材料来创建和迭代材料集合&#xff0c;从而轻松将真实的图片转换为具有真实感的表面…