#if UNITY_EDITOR
using System.IO;
using System.Collections;
using Unity.EditorCoroutines.Editor;
using UnityEditor;
using UnityEngine;
using UnityEngine.Networking;
public static class DownloadAndSaveImageEditor
{
[MenuItem("Custom/Download And Save Image")]
public static void DownloadAndSave()
{
string imageUrl = EditorGUIUtility.systemCopyBuffer;
string pathToSaveImage = Application.dataPath;
EditorCoroutineUtility.StartCoroutineOwnerless(DownloadAndSaveRoutine(imageUrl, pathToSaveImage, (texture) =>
{
Debug.Log("Image saved!");
}));
}
public static IEnumerator DownloadAndSaveRoutine(string imageUrl, string pathToSaveImage, System.Action<Texture2D> onCompleted)
{
using (UnityWebRequest www = UnityWebRequestTexture.GetTexture(imageUrl))
{
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.Log(www.error);
}
else
{
var texture = DownloadHandlerTexture.GetContent(www);
byte[] bytes;
bytes = texture.EncodeToPNG();
string path = Path.Combine(pathToSaveImage, "DownloadedImage.png");
File.WriteAllBytes(path, bytes);
onCompleted?.Invoke(texture);
}
}
}
}
#endif