Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- using System.IO;
- using Unity.VisualScripting;
- public class FetchImages : MonoBehaviour
- {
- public string imagesUrl = "https://gementar.com/qar_en_nizam/";
- private string[] imageUrls;
- private string localFolderPath;
- public int totalImages;
- public int currentImages;
- void Start()
- {
- localFolderPath = Path.Combine(Application.persistentDataPath, "Images");
- if (!Directory.Exists(localFolderPath))
- {
- Directory.CreateDirectory(localFolderPath);
- }
- Debug.Log("Data Path : " + Application.persistentDataPath);
- StartCoroutine(GetImageUrls());
- }
- private bool downloadFinishedOneTimeTrigger = true;
- private bool canCount = false;
- private void Update()
- {
- if(isDownloadFinished() && downloadFinishedOneTimeTrigger && canCount)
- {
- Debug.Log("Finished");
- downloadFinishedOneTimeTrigger = false;
- }
- }
- private bool isDownloadFinished()
- {
- if (currentImages >= totalImages)
- {
- return true;
- }
- return false;
- }
- IEnumerator GetImageUrls()
- {
- WWW www = new WWW(imagesUrl);
- yield return www;
- string html = www.text;
- imageUrls = ParseImageUrls(html);
- foreach (string url in imageUrls)
- {
- StartCoroutine(DownloadImage(url));
- }
- }
- string[] ParseImageUrls(string html)
- {
- string[] splitHtml = html.Split('"');
- ArrayList urls = new ArrayList();
- for (int i = 0; i < (splitHtml.Length); i++)
- {
- if (splitHtml[i].EndsWith(".jpg") || splitHtml[i].EndsWith(".png"))
- {
- if (splitHtml[i].StartsWith("/")) continue;
- urls.Add(imagesUrl + splitHtml[i]);
- totalImages++;
- }
- }
- canCount = true;
- return (string[])urls.ToArray(typeof(string));
- }
- IEnumerator DownloadImage(string imageUrl)
- {
- string filename = GetFileNameFromUrl(imageUrl);
- string localFilePath = Path.Combine(localFolderPath, filename);
- if (!File.Exists(localFilePath))
- {
- using (WWW www = new WWW(imageUrl))
- {
- yield return www;
- if (www.error == null)
- {
- File.WriteAllBytes(localFilePath, www.bytes);
- Debug.Log("Downloaded: " + imageUrl);
- }
- else
- {
- Debug.Log("Error downloading: " + imageUrl + " - " + www.error);
- }
- }
- }
- else
- {
- Debug.Log("File already exists: " + imageUrl);
- }
- currentImages++;
- }
- string GetFileNameFromUrl(string url)
- {
- int index = url.LastIndexOf("/") + 1;
- return url.Substring(index, url.Length - index);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement