NEWS

[C#] Lấy và download tất cả link hình ảnh từ đường dẫn website

[C#] Lấy và download tất cả link hình ảnh từ đường dẫn website
Đăng bởi: Thảo Meo - Lượt xem: 6563 09:26:02, 11/06/2021C#   In bài viết

Xin chào các bạn, bài viết hôm nay mình sẻ tiếp tục hướng dẫn các bạn cách get link tất cả hình ảnh từ một đường dẫn website trên lập trình C#, Winform.

[C#] Download All Image From Link Website

Dưới đây là giao diện demo ứng dụng tải tất cả hình ảnh từ website:

fetch_all_image_csharp

  1. Đầu tiên, các bạn chọn đường dẫn vào và bấm nút Get Images => trả về danh sách các đường dẫn hình ảnh từ link URL.
  2. Tiếp đến các bạn bấm nút Download All để tải hình ảnh về ổ đĩa máy tính của bạn.

fetch_all_image

Full source code Download Image C#:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FetchAllImageFromWebsite
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        }

        private void btnGetImages_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            listImages.Items.Clear();

            foreach (string image in FetchImages(txtURL.Text))
            {
                listImages.Items.Add(image);
            }

            this.Cursor = Cursors.Default;
        }

        public List<string> FetchImages(string Url)
        {
            List<string> imageList = new List<string>();
         
            if (!Url.StartsWith("http://") && !Url.StartsWith("https://"))
                Url = "http://" + Url;
           
             var htmlDoc = new HtmlAgilityPack.HtmlWeb().Load(Url);
            var htmlData = htmlDoc.DocumentNode.OuterHtml;
            string imageHtmlCode = "<img";
            string imageSrcCode = @"src=""";

            int index = htmlData.IndexOf(imageHtmlCode);
            while (index != -1)
            {
                //Remove previous data
                htmlData = htmlData.Substring(index);

                //Find the location of the two quotes that mark the image's location
                int brackedEnd = htmlData.IndexOf('>'); //make sure data will be inside img tag
                int start = htmlData.IndexOf(imageSrcCode) + imageSrcCode.Length;
                int end = htmlData.IndexOf('"', start + 1);

                //Extract the line
                if (end > start && start < brackedEnd)
                {
                    string loc = htmlData.Substring(start, end - start);

                    //Store line
                    imageList.Add(loc);
                }

                //Move index to next image location
                if (imageHtmlCode.Length < htmlData.Length)
                    index = htmlData.IndexOf(imageHtmlCode, imageHtmlCode.Length);
                else
                    index = -1;
            }

            //Format the image URLs
            for (int i = 0; i < imageList.Count; i++)
            {
                string img = imageList[i];

                string baseUrl = GetBaseURL(Url);

                if ((!img.StartsWith("http://") && !img.StartsWith("https://"))
                    && baseUrl != string.Empty)
                    img = baseUrl + "/" + img.TrimStart('/');

                imageList[i] = img;
            }
            return imageList;
        }

        private string GetBaseURL(string Url)
        {
            int inx = Url.IndexOf("://") + "://".Length;
            int end = Url.IndexOf('/', inx);

            string baseUrl = string.Empty;
            if (end != -1)
                return Url.Substring(0, end);
            else
                return string.Empty;
        }

        private void listImages_SelectedValueChanged(object sender, EventArgs e)
        {
            string curItem = listImages.SelectedItem.ToString();
            picImage.LoadAsync(curItem);
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            var firstname = "";
            foreach(var item in listImages.Items)
            {
                using (WebClient webClient = new WebClient())
                {
                    try
                    {
                        string fileName = Path.GetFileName(new UriBuilder(item.ToString()).Path);
                        webClient.DownloadFile(item.ToString(), "images\\" + fileName);
                        firstname = fileName;

                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                  
                }
            }

            ExploreFile(Application.StartupPath + $"\\images\\{firstname}");


        }

        public bool ExploreFile(string filePath)
        {
            if (!System.IO.File.Exists(filePath))
            {
                return false;
            }

            filePath = System.IO.Path.GetFullPath(filePath);
            System.Diagnostics.Process.Start("explorer.exe", string.Format("/select,\"{0}\"", filePath));
            return true;
        }
    }
}

Thanks for watching!

DOWNLOAD SOURCE

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Lấy và download tất cả link hình ảnh từ đường dẫn website
Đăng bởi: Thảo Meo - Lượt xem: 6563 09:26:02, 11/06/2021C#   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.